在react类组件中绑定事件时遇到undefined的问题,可以用以下四种方式解决。
先做个案例,改变按钮的value值
- 通过箭头函数解决
<script type="text/babel">
class App extends React.Component{
constructor(props){
super(props)
this.state = {
n:1
}
}
render(){
return <div>
<input type="button" value={this.state.n}
onClick={()=>{
this.setState({
n:this.state.n+1
})
}} />
</div>
}
}
ReactDOM.render(<App />,document.querySelector("#box"))
</script>
注意:当逻辑不太复杂,不会重复使用
- 直接通过bind绑定this
<script type="text/babel">
class App extends React.Component{
constructor(props){
super(props)
this.state = {
n:1
}
}
change(){
this.setState({
n:this.state.n+1
})
}
render(){
return <div>
<input type="button" value={this.state.n}
onClick={this.change.bind(this)}/>
</div>
}
}
ReactDOM.render(<App />,document.querySelector("#box"))
</script>
注意:当方法使用频率不高时,建议使用该方法。
3.通过在构造器当中提前绑定好,在使用时直接调用
<script type="text/babel">
class App extends React.Component{
constructor(props){
super(props)
this.state = {
n:1
}
this.change = this.change.bind(this)
}
change(){
this.setState({
n:this.state.n+1
})
}
render(){
return <div>
<input type="button" value={this.state.n}
onClick={this.change}/>
</div>
}
}
ReactDOM.render(<App />,document.querySelector("#box"))
</script>
注意:当你在多处使用时,后面不需要再次使用bind绑定this,问题是传值不方便。
- 将函数直接定义为箭头函数
<script type="text/babel">
class App extends React.Component{
constructor(props){
super(props)
this.state = {
n:1
}
}
change=()=>{
this.setState({
n:this.state.n+1
},()=>{
// 更新完数据执行该函数
console.log(this.state.n)
})
}
render(){
return <div>
<input type="button" value={this.state.n}
onClick={()=>this.change()}/>
</div>
}
}
ReactDOM.render(<App />,document.querySelector("#box"))
</script>
注意:需要传递参数,不要使用该方法。