this.onClick无法绑定

#1
import React, {Component} from 'react'
import ProTypes from 'prop-types'

class Counter extends Component{
    constructor(props){
        super(props)
        //这里提前绑定了this,所以不需要再去绑定什么
        this.inscrementAsync = this.inscrementAsync.bind(this)
        this.inscrementIfOdd = this.inscrementIfOdd.bind(this)
    }
    inscrementIfOdd(){
        if(this.props.value % 2 !== 0){ //奇数就增加
            this.props.onIncrement()
            console.log(11)
        }
        console.log(44)
    }

    inscrementAsync(){
        console(33)
        setTimeout(this.props.onIncrement, 1000)
        console.log(22)
    }
    render(){
        const {value , onIncrement , onDecrement} = this.props
        return(
            <p>
                Clicked: {value} times
                {' '}
                <button onClick={onIncrement}>
                +
                </button>
                {' '}
                <button onClick={onDecrement}>
                -
                </button>
                {' '}
                <button onClick={this.incrementIfOdd}>
                Increment if odd
                </button>
                {' '}
                <button onClick={this.incrementAsync}>
                Increment async
                </button>
            </p>
        )
    }
}
export default Counter

我在这里使用了es6的语法,所以无法自动绑定bind,想了解一下为什么click之后不能调用console函数,这里的11 22 33 44都无法返回


分享一个链接,关于es6不能自动绑定https://stackoverflow.com/questions/39632811/cannot-read-property-bind-of-undefined-react-js

#2

                Increment async
                

这样写不行吗?

#3


你看,官方文档里都有的哦小哥

2 Likes
#4

好像不可以哦,因为同时有es5 es6的语法,es6里面取消了bind的绑定

#5

:grinning::grinning:谢了啊 :slight_smile::grinning:

#6
<button onClick={this.incrementIfOdd}>


incrementIfOdd = () => {
  this 可以用
}
1 Like
#7

是的,因为es6取消了关于bind的绑定,你的箭头函数就是es6语法

#8

说点什么好呢,实质是一个s引发的问题,且看下面解答

一句忠告:写代码的时候注意细节

上面各位大神提的方法按理都是可行的。下面说说代码的问题吧

  1. props接收value,onIncrement,onDecrement这三个,建议proptypes添加类型校验,养成好习惯

  2. inscrementAsync函数中,应该为console.log而不是console

  3. 导致你提问的根源。函数声明和函数调用函数名不一样,一个为inscrementAsync,另一个为incrementAsync。一个s引发的问题

1 Like
#9

感谢建议,学习了