Estoy usando el siguiente código. Dentro del componente ContentTwo, hay un botón, quiero que pueda activar la misma función que el botón en el renderizado, cuando es el contenido en vivo. ¿Cómo haría esto?
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') );Puede pasar this.handleClick a ContentTwo y acceder a él desde los accesorios:
<ContentTwo handleClick={this.handleCLick} />y entonces
function ContentTwo(props) { return(<button onClick={props.handleClick}>Swap like the other button</button> );