生活随笔
收集整理的這篇文章主要介紹了
[react] react有几种构建组件的方式?可以写出来吗?
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
[react] react有幾種構(gòu)建組件的方式?可以寫出來嗎?
1.無狀態(tài)函數(shù)式組件
?
function HelloComponent(props, /* context */) {
return <div>Hello {props.name}</div>
}
ReactDOM.render(<HelloComponent name="Sebastian" />, mountNode)
2.React.createClass
?
var InputControlES5 = React.createClass({
propTypes: {//定義傳入props中的屬性各種類型
initialValue: React.PropTypes.string
},
defaultProps: { //組件默認的props對象
initialValue: ''
},
// 設(shè)置 initial state
getInitialState: function() {//組件相關(guān)的狀態(tài)對象
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:
<input onChange={this.handleChange} value={this.state.text} />
</div>
);
}
});
InputControlES6.propTypes = {
initialValue: React.PropTypes.string
};
InputControlES6.defaultProps = {
initialValue: ''
};
3.React.Component
?
class InputControlES6 extends React.Component {
constructor(props) {
super(props);// 設(shè)置 initial state
this.state = {
text: props.initialValue || 'placeholder'
};// ES6 類中函數(shù)必須手動綁定
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: ''
};
個人簡介
我是歌謠,歡迎和大家一起交流前后端知識。放棄很容易,
但堅持一定很酷。歡迎大家一起討論
主目錄
與歌謠一起通關(guān)前端面試題
總結(jié)
以上是生活随笔為你收集整理的[react] react有几种构建组件的方式?可以写出来吗?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。