本文主要跟大家分享了ES6下React組件的寫法示例,下面來一起看看詳細(xì)的介紹:
一:定義React組件
class Hello extends React.Component { render() { return <h1>Hello, {this.props.value}</h1>; }}
二:聲明prop類型與默認(rèn)prop
class Hello extends React.Component { // ...}Hello.propTypes = { value: React.PropTypes.string};Hello.defaultProps = { value: 'world'};
三、設(shè)置初始state
class Hello extends React.Component { constructor(props) { super(props); this.state = {count: props.initialCount}; } // ...}
四、自動(dòng)綁定
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> ); }}
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對(duì)武林網(wǎng)的支持。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注