1、 在调用的时候使用 bind 绑定 this
import React from 'react'
export default class Child2 extends React.Component{
constructor(props){
super(props)
this.state = {
name:'aaa'
}
}
handleName(){
this.setState({
name:'ks'
})
}
render(){
return (
<div>
{this.state.name}
<button onClick = {this.handleName.bind(this)}>name</button>
</div>
)
}
}
2、在构造函数中使用 bind 绑定 this
import React from 'react'
export default class Child2 extends React.Component{
constructor(props){
super(props)
this.state = {
name:'aaa'
}
this.handleName = this.handleName.bind(this);
}
handleName(){
this.setState({
name:'ks'
})
}
render(){
return (
<div>
{this.state.name}
<button onClick = {this.handleName}>name</button>
</div>
)
}
}
3、使用箭头函数绑定 this
import React from 'react'
export default class Child2 extends React.Component{
constructor(props){
super(props)
this.state = {
name:'aaa'
}
}
handleName(){
this.setState({
name:'ks'
})
}
render(){
return (
<div>
{this.state.name}
<button onClick = {(e) => this.handleName(e)}>name</button>
</div>
)
}
}
4、public class fields 型
import React from 'react'
export default class Child2 extends React.Component{
constructor(props){
super(props)
this.state = {
name:'aaa'
}
}
handleName = ()=>{
this.setState({
name:'ks'
})
}
render(){
return (
<div>
{this.state.name}
<button onClick = {this.handleName}>name</button>
</div>
)
}
}