本文主要跟大家分享了ES6下React組件的寫法示例,下面來一起看看詳細的介紹:
一:定義React組件
class Hello extends React.Component { render() { return <h1>Hello, {this.props.value}</h1>; }}
二:聲明prop類型與默認prop
class Hello extends React.Component { // ...}Hello.propTypes = { value: React.PropTypes.string};Hello.defaultProps = { value: 'world'};
三、設置初始state
class Hello extends React.Component { constructor(props) { super(props); this.state = {count: props.initialCount}; } // ...}
四、自動綁定
class SayHello extends React.Component { constructor(props) { super(props); this.state = {message: 'Hello!'}; // 這行很重要 this.handleClick = this.handleClick.bind(this); } handleClick() { alert(this.state.message); } render() { // Because `this.handleClick` is bound, we can use it as an event handler. return ( <button onClick={this.handleClick}> Say hello </button> ); }}
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對武林網的支持。
新聞熱點
疑難解答