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

React中父组件通过Props向子组件传值:点击按钮传递邮箱值

把邮箱值传递给子组件的简单方法

嘿,你已经成功把theExpert.email存到父组件的state.exp里了,接下来把这个值传给子组件其实非常直接,分两步就能搞定:

  • 第一步:在父组件里给子组件传递props
    确保你在父组件的render方法里渲染子组件时,把state里的exp作为props传进去。比如假设你的子组件叫ExpertInfo,代码可以写成这样:

    render() {
      return (
        <div>
          {/* 其他父组件内容 */}
          <ExpertInfo expertEmail={this.state.exp} />
        </div>
      );
    }
    

    这里的expertEmail是你给props起的名字,你可以根据需求改成更贴合业务的命名,比如targetEmail都行。

  • 第二步:在子组件里接收并使用这个props
    根据你的子组件是类组件还是函数组件,接收方式略有不同:

    • 如果是类组件:通过this.props来访问传递过来的值
      class ExpertInfo extends React.Component {
        render() {
          return (
            <div>
              选中的专家邮箱:{this.props.expertEmail}
            </div>
          );
        }
      }
      
    • 如果是函数组件:直接解构props或者通过参数访问
      // 解构写法(更简洁)
      const ExpertInfo = ({ expertEmail }) => {
        return <div>选中的专家邮箱:{expertEmail}</div>;
      };
      
      // 或者直接用props参数
      const ExpertInfo = (props) => {
        return <div>选中的专家邮箱:{props.expertEmail}</div>;
      };
      

另外要补充一句:因为你在hideButton里用setState更新了exp的值,React会自动触发父组件的重新渲染,子组件也会同步拿到最新的expertEmail props,完全不需要手动做额外的更新操作哦~

内容的提问来源于stack exchange,提问作者M.A.G

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:57:44