react 中创建组件的几种方式
更多见添加的文章连接。
一、函数式组件
函数组件不涉及state状态的改变,只用一个render的方法,输出样式。
function HelloComponent(props,/* context */)
{return<div>Hello{props.name}</div>}
ReactDOM.render(<HelloComponent name="Sebastian" />, mountNode) 缺点: 无法访问this,无法访问生命周期函数,只能访问props的数据。
二、类class组件 Es5初代语法。以下两种都可以弥补函数组件的缺点,却也加大了内部程序运行开销
var InputControlES5 =React.createClass({
propTypes:{//定义传入props中的属性各种类型
initialValue:React.PropTypes.string
},
defaultProps:{//组件默认的props对象
initialValue:""
},
// 设置 initial state
getInitialState:function(){//组件相关的状态对象
return{
text:this.props.initialValue||"placeholder"
};
},
handleChange:function(event){
this.setState({//this represents react component instance
text:event.target.value
});
},
render:function(){
return (
<div> Type something:
<inputonChange={this.handleChange}value={this.state.text}/>
</div> );
}});
InputControlES6.propTypes={
initialValue:React.PropTypes.string};
InputControlES6.defaultProps={initialValue:""};三、Es6初代语法
class InputControlES6 extends React.Component {
constructor(props) {
super(props);
// 设置 initial state
this.state = {
text: props.initialValue || "placeholder"
};
// ES6 类中函数必须手动绑定
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({
text: event.target.value
});
}
render() {
return (
<div>
Type something:
<input onChange={this.handleChange}
value={this.state.text} />
</div>
);
}
}
InputControlES6.propTypes = {
initialValue: React.PropTypes.string
};
InputControlES6.defaultProps = {
initialValue: ""
};React.Component 有三种函数绑定的方式:
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: React学习笔记——如何创建React组件
- 下一篇: PlY文件读取显示
copyright © 2008-2019 亿联网络 版权所有 备案号:粤ICP备14031511号-2
