React中父組件如何獲取子組件的值或方法
父組件獲取子組件的值或方法
先來說下從哪獲取的啟發(fā),想要從父組件獲取子組件的值或方法。。。
一次寫代碼的時候,用 Antd 中的 Modal 包裹了一個子組件,子組件中包含 input 輸入框,想要在點(diǎn)擊對話框上面確定按鈕時(即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();
方法三
在父組件創(chuàng)建ref容器:this.pw = React.createRef()
constructor(props) {
? ? super(props);
? ? // 方法3:創(chuàng)建用來保存ref標(biāo)識的標(biāo)簽對象的容器
? ? 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函數(shù)式組件傳值之子傳父
在用react進(jìn)行函數(shù)式編程時,父組件可以通過props向子組件傳值,那么子組件怎么向父組件傳值呢?
首先,父組件需要向子組件傳遞一個函數(shù),然后,子組件通過props獲取函數(shù)并附上參數(shù),最后,父組件通過函數(shù)拿到子組件傳遞的值。
具體案例
父組件: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>子組件傳過來的數(shù)字:{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>數(shù)字:{count}</p>
<button onClick={() => addCount(count + 1)}>數(shù)字遞增</button>
</div>
);
};
export default Child;效果展示

以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
webpack4+react多頁面架構(gòu)的實(shí)現(xiàn)
webpack在單頁面打包上應(yīng)用廣泛,以create-react-app為首的腳手架眾多。這篇文章主要介紹了webpack4+react多頁面架構(gòu)的實(shí)現(xiàn),具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-10-10
簡析React Native startReactApplication 方法
這篇文章主要介紹了React Native startReactApplication 方法簡析,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-09-09
解決React報錯Expected?`onClick`?listener?to?be?a?function
這篇文章主要為大家介紹了React報錯Expected?`onClick`?listener?to?be?a?function解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12
React組件實(shí)例三大屬性state props refs使用詳解
這篇文章主要為大家介紹了React組件實(shí)例三大屬性state props refs使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09
詳解React中傳入組件的props改變時更新組件的幾種實(shí)現(xiàn)方法
這篇文章主要介紹了詳解React中傳入組件的props改變時更新組件的幾種實(shí)現(xiàn)方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-09-09

