Consider the app:
function App() {
return (
<div>
<ComponentOne/>
<ComponentTwo/>
</div>
);
}
export default App;
with ComponentTwo
as:
class ComponentTwo extends React.Component{
constructor(){
super();
window.handleClick = this.handleClick;
}
handleClick = function(){alert('hello');}
render(){return null;}
}
Why is it that this works:
class ComponentOne extends React.Component{
handleClick(){window.handleClick();}
render(){return <input type="submit" onClick={this.handleClick}/>;}
}
but not this:
// no error, but does not work
class ComponentOne extends React.Component{
render(){return <input type="submit" onClick={window.handleClick}/>;}
}
or this:
// gives an error when the "input button" is clicked saying ComponentTwo.handleClick is not a function
class ComponentOne extends React.Component{
handleClick(){ComponentTwo.handleClick();}
render(){return <input type="submit" onClick={this.handleClick}/>;}
}
Also in the first case, where it works, using a global (if I understand correctly) window.handleClick
doesn't seem like a good practice. Is there a better way? Or, what is the "best practice" method of handling "click on one component changes the state of the other component"?
I'm not sure I am missing something - haven't done any serious JS programming; only used vanilla JS and jquery for manipulating DOM components so far. So, I'd be glad to know that as well. Thank you.
PS: I got the first method from here.