1.bind绑定的方法、
不传参
class Hello extends React.Component{ constructor(){ super() this.state = { content:true } this.change = this.change.bind(this) } change(){ this.setState({ content:!this.state.content }) } render(){ return ( <div> <h1>{this.state.content ? '1':'2'}</h1> <h2>{this.props.name}</h2> <button onClick={this.change}> 点击 </button> </div> ) } } ReactDOM.render( <Hello name="Hello"/>, document.getElementById('example') )
传参
class Hello extends React.Component{ constructor(){ super() this.state = { content:true } this.change = this.change.bind(this,this.state.content) } change(obj){ this.setState({ content:!this.state.content }) console.log(obj) console.log(this.state.content) } render(){ return ( <div> <h1>{this.state.content ? '1':'2'}</h1> <h2>{this.props.name}</h2> <button onClick={this.change}> 点击 </button> </div> ) } } ReactDOM.render( <Hello name="Hello"/>, document.getElementById('example') )
2.属性初始化器的方式
不传参
class Hello extends React.Component{ constructor(){ super() this.state = { content:true } } change=()=>{ this.setState({ content:!this.state.content }) } render(){ return ( <div> <h1>{this.state.content ? '1':'2'}</h1> <h2>{this.props.name}</h2> <button onClick={this.change}> 点击 </button> </div> ) } } ReactDOM.render( <Hello name="Hello"/>, document.getElementById('example') )
传参
class Hello extends React.Component{ constructor(){ super() this.state = { content:true } } change=obj=>{ this.setState({ content:!this.state.content }) console.log(obj) } render(){ return ( <div> <h1>{this.state.content ? '1':'2'}</h1> <h2>{this.props.name}</h2> <button onClick={this.change(this.state.content)}> 点击 </button> </div> ) } } ReactDOM.render( <Hello name="Hello"/>, document.getElementById('example') )
3.回调函数的方式
不传参
class Hello extends React.Component{ constructor(){ super() this.state = { content:true } } change(){ this.setState({ content:!this.state.content }) } render(){ return ( <div> <h1>{this.state.content ? '1':'2'}</h1> <h2>{this.props.name}</h2> <button onClick={()=>{this.change()}}> 点击 </button> </div> ) } } ReactDOM.render( <Hello name="Hello"/>, document.getElementById('example') )
传参
class Hello extends React.Component{ constructor(){ super() this.state = { content:true } } change(obj){ this.setState({ content:!this.state.content }) console.log(obj) } render(){ return ( <div> <h1>{this.state.content ? '1':'2'}</h1> <h2>{this.props.name}</h2> <button onClick={()=>{this.change(this.state.content)}}> 点击 </button> </div> ) } } ReactDOM.render( <Hello name="Hello"/>, document.getElementById('example') )