You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何在条件渲染的ContentTwo组件内触发父组件的onClick方法

实现方案

当前代码无法生效的核心原因:

  1. 函数组件ContentTwo内部不存在独立的this指向,直接写this.handleClick会读取到undefined
  2. 父组件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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 16:24:08