I'm using the following code. Inside the ContentTwo component, there is a button, I want it to be able to trigger the same function as the button in the render, when it is the live content. How would I go about this?
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
return (
<div >
{this.state.isToggleOn ? <ContentOne /> : <ContentTwo />}
<button onClick={this.handleClick}>Swap</button>
</div>
);
}
}
function ContentOne(props) {
return(<h1>Content One</h1>
);
}
function ContentTwo(props) {
return(<button onClick={this.handleClick}>Swap like the other button</button>
);
}
ReactDOM.render(
<Toggle />,
document.getElementById('root')
);
CodePudding user response:
You could pass the this.handleClick to ContentTwo and access it from the props:
<ContentTwo handleClick={this.handleCLick} />
and then
function ContentTwo(props) {
return(<button onClick={props.handleClick}>Swap like the other button</button>
);