<分区>
可以在下面的链接中找到一个可用的 WebpackBin,
https://www.webpackbin.com/bins/-Kibrw5tNNrsQpENUv_M
我有两个组件。父组件通过 prop 将函数传递给子组件,子组件的事件处理程序通过 func.bind(null, num)
调用传入的函数以提供额外的预设参数。
为什么 dummyFunc.bind(null, 666)
有效,不应该 bind
使新创建的函数 this
context 变为 null
?因此,每个 this.setState
都应该变成未定义的。
父组件代码,
import React from 'react'
import Component from './Component'
export default class Hello extends React.Component {
constructor(props) {
super(props)
this.state = {
foo: 2
}
this.foo = this.foo.bind(this)
}
foo(newValue) {
this.setState({
foo: newValue + this.state.foo
})
console.log(this.state.foo)
}
render() {
return (
<div>
<h1>App</h1>
<Component dummyFunc={this.foo} />
</div>
)
}
}
子组件代码,
import React from 'react'
const Component = ({dummyFunc}) => {
return (
<div>
<button onClick={dummyFunc.bind(null, 666)}>BUTTON</button>
</div>
)
}
export default Component