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