I have a component (Component1) which I want to call a function from another (in this case the main app). My question is why the onClickMe function can't access this from App component ?
class Component1 extends React.Component {
render() {
return (
<div>
<h5>sub Component 1 </h5>
<button onClick={() => this.props.data[0].action("foo")}>
Click Me!
</button>
</div>
);
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = { clicked: false };
this.onClickMe = this.onClickMe.bind(this);
}
data = [{ name: "Giordano", action: this.onClickMe }];
onClickMe(value) {
/// I can get the correct value here
console.log(value);
/// THIS IS THE PROBLEM.
/// "this" here refers to the object `data` not App
/// so there is no 'setState' function on this
this.setState({ clicked: true });
}
render() {
return (
<div>
<h1>Main page</h1>
<Component1 data={this.data} />
</div>
);
}
}
the code example : https://codesandbox.io/s/react-playground-forked-99kumd?file=/index.js