react类组件关于事件undefined的问题解决方法

在react类组件中绑定事件时遇到undefined的问题,可以用以下四种方式解决。

先做个案例,改变按钮的value值

  1. 通过箭头函数解决
<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>

注意:当逻辑不太复杂,不会重复使用

  1. 直接通过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,问题是传值不方便。

  1. 将函数直接定义为箭头函数
<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>

注意:需要传递参数,不要使用该方法。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值