This is a simple React app that I just generated with create-react-app
, and modified only App.js
to what you see below. This is an exercise to see if I understand bind
enough to get results I expect as I toy with it. I'm not getting the expected result: I bind method
in the class to obj
, and use an onClick
on a div to execute this bound method
. In the method definition, I am calling this.setState
, and setState
is defined on obj
, but I get an error that this.state
is undefined in the setState
method definition. Why?
import React from 'react';
import './App.css';
const Button = ({ onClick, quantity }) => <div onClick={onClick} style={{ width: 40 , height: 20}}>{quantity}</div>;
const generateButton = (quantity, onClick) => () => <Button onClick={() => onClick(quantity)} quantity={quantity} />
const obj = {
state: { count: 1000 },
setState: ({ count }) => this.state.count += count
};
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
}
this.method = this.method.bind(obj);
}
method(count) {
const newCount = this.state.count + count;
this.setState({ count: newCount})
}
render() {
return (
<div>
<div style={{width: 100, height: 100, fontSize: 50}}>{obj.state.count}</div>
{generateButton(10, this.method)()}
</div>
)
}
}
export default App;