React中如何在条件渲染的ContentTwo组件内触发父组件的onClick方法
实现方案
当前代码无法生效的核心原因:
- 函数组件
ContentTwo内部不存在独立的this指向,直接写this.handleClick会读取到undefined - 父组件
Toggle的handleClick方法没有传递给子组件,子组件没有权限直接访问父组件的内部方法
具体修改步骤
- 第一步:修改父组件
Toggle的render逻辑,给<ContentTwo />传递props,把handleClick方法传入
原代码行:
修改为:{this.state.isToggleOn ? <ContentOne /> : <ContentTwo />}{this.state.isToggleOn ? <ContentOne /> : <ContentTwo handleClick={this.handleClick} />} - 第二步:修改
ContentTwo组件,接收props参数,绑定内部按钮的点击事件
原代码:
修改为:function ContentTwo(props) { return(<button onClick={this.handleClick}>Swap like the other button</button>); }function ContentTwo(props) { return(<button onClick={props.handleClick}>Swap like the other button</button>); }
修改后完整可运行代码
class Toggle extends React.Component { constructor(props) { super(props); this.state = {isToggleOn: true}; this.handleClick = this.handleClick.bind(this); } handleClick() { this.setState(prevState => ({ isToggleOn: !prevState.isToggleOn })); } render() { return ( <div > {this.state.isToggleOn ? <ContentOne /> : <ContentTwo handleClick={this.handleClick} />} <button onClick={this.handleClick}>Swap</button> </div> ); } } function ContentOne(props) { return(<h1>Content One</h1>); } function ContentTwo(props) { return(<button onClick={props.handleClick}>Swap like the other button</button>); } ReactDOM.render( <Toggle />, document.getElementById('root') );
修改后两个按钮的点击逻辑完全一致,点击任意一个都可以切换两个内容组件的渲染状态。
内容的提问来源于stack exchange,提问作者chris
相关产品推荐
相关产品推荐

