React建立元件的三種方式
阿新 • • 發佈:2019-02-08
無狀態函式式元件
建立無狀態函式式元件形式是從React
0.14
版本開始出現的。它是為了建立純展示元件,這種元件只負責根據傳入的props
來展示,不涉及到要state
狀態的操作。
function HelloComponent(props, /* context */) {
return <div>Hello {props.name}</div>
}
ReactDOM.render(<HelloComponent name="Sebastian" />, mountNode)
Es6箭頭函式寫法
一定要注意使用var let const 來宣告否則無用const FindComponent=()=> { return <div>OH!</div> }
React.createClass
`React.createClass`是react剛開始推薦的建立元件的方式,這是ES5的原生的JavaScript來實現的React元件但現在基本不用React也會慢慢將其淘汰
React.Component
React.Component
是以ES6的形式來建立react的元件的,是React目前極為推薦的建立有狀態元件的方式,最終會取代React.createClass
形式;相對於 React.createClass
可以更好實現程式碼複用。將上面React.createClass
的形式改為React.Component
形式如下: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: '' };