React中父组件怎么获取子组件的值或方法

这篇“React中父组件怎么获取子组件的值或方法”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“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()

React函数式组件传值之子传父

在用react进行函数式编程时,父组件可以通过props向子组件传值,那么子组件怎么向父组件传值呢?

首先,父组件需要向子组件传递一个函数,然后,子组件通过props获取函数并附上参数,最后,父组件通过函数拿到子组件传递的值。

具体案例

父组件:home.tsx

import React, { useState } from 'react';
import Child from './component/child';
import './index.less';
 
const Home: React.FC = () => {
  const [parentCount, setParentCountt] = useState<number>(0);
 
  const getChildCount = (val: number) => {
    setParentCountt(val);
  };
 
  return (
    <div className="home-wrap">
      <p>我是父组件</p>
      <p>子组件传过来的数字:{parentCount}</p>
      <Child getCount={getChildCount} />
    </div>
  );
};
 
export default Home;

子组件:child.tsx

import React, { useState } from 'react';
 
type selfProps = {
  getCount: Function;
};
 
const Child: React.FC<selfProps> = (props) => {
  const { getCount } = props;
  const [count, setCount] = useState<number>(0);
 
  const addCount = (val: number) => {
    setCount(val);
    getCount(val);
  };
 
  return (
    <div className="child-wrap">
      <p>子组件</p>
      <p>数字:{count}</p>
      <button onClick={() => addCount(count + 1)}>数字递增</button>
    </div>
  );
};
 
export default Child;

效果展示

React中父组件怎么获取子组件的值或方法  react 第1张

以上就是关于“React中父组件怎么获取子组件的值或方法”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注蜗牛博客行业资讯频道。

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:niceseo99@gmail.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

评论

有免费节点资源,我们会通知你!加入纸飞机订阅群

×
天气预报查看日历分享网页手机扫码留言评论电报频道链接