A working WebpackBin can be found at link below,
https://www.webpackbin.com/bins/-Kibrw5tNNrsQpENUv_M
I have two components. Parent component pass a function to its child component via prop and child component's event handler invoke the passed in function via func.bind(null, num)
to provide extra pre-set argument.
Why dummyFunc.bind(null, 666)
works, should not bind
make the newly created function this
context become null
? Hence, every this.setState
should become undefined.
Parent Component Code,
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>
)
}
}
Child Component Code,
import React from 'react'
const Component = ({dummyFunc}) => {
return (
<div>
<button onClick={dummyFunc.bind(null, 666)}>BUTTON</button>
</div>
)
}
export default Component