关键词搜索

全站搜索
×
密码登录在这里
×
注册会员

已有账号? 请点击

忘记密码

已有账号? 请点击

使用其他方式登录

React父组件获取子组件的值和方法

发布2022-05-12 浏览1750次

详情内容

在使用React开发时,经常到到父子组件间传值,先来说下从哪获取的启发,想要从父组件获取子组件的值或方法。

一次写代码的时候,用 Antd 中的 Modal 包裹了一个子组件,子组件中包含 input 输入框,想要在点击对话框上面确定按钮时(即Modal 自带的 onOk方法),拿到其中输入的值,,,,

 

下面用一个父组件(Father.js)和子组件(Hearder.js)来演示如何能拿到值和方法:

方法一:

给子组件添加属性 ref='footer'

<Header ref='footer'></Header>

 然后在父组件用 this.refs.footer.xxx 的方式拿值

alert(this.refs.footer.state.sonmsg);//拿到子组件中state中的值
this.refs.footer.run();//拿到子组件中runn方法

 

方法二:

给子组件添加 onRef={(ref) => { this.child = ref; }}

<Header onRef={(ref) => { this.child = ref; }}></Header>

然后在子组件中添加生命周期的 componentDidMount 这个方法:

componentDidMount() {
     if (this.props.onRef) {
        this.props.onRef(this);
     }
}

然后在父组件用 this.child.xxx 的方式拿值

alert(this.child.state.sonmsg);
this.child.run();

 

方法三:

在父组件创建ref容器:this.pw = React.createRef()

constructor(props) {
    super(props);
    // 方法3:创建用来保存ref标识的标签对象的容器
    this.pw = React.createRef()
}

然后给子组件添加属性:ref={this.pw}

<Header ref={this.pw}></Header>

然后就可以在父组件用 this.pw.current 拿到子组件值和方法:

alert(this.pw.current.state.sonmsg); 
this.pw.current.run()

 

点击QQ咨询
开通会员
上传资源赚钱
返回顶部
×
  • 微信支付
  • 支付宝付款
扫码支付
微信扫码支付
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载