React通過ref獲取子組件的數(shù)據(jù)和方法
父組件
1) ref必須傳值, 否則childRef拿不到子組件的數(shù)據(jù)和方法
注意: 不一定使用app組件, 其他的任何父組件都可以
import "./App.css";
import React, { useEffect, useRef } from "react";
import RefToGetChild from "./components/RefToGetChild";
import _ from 'lodash';
const App: React.FC = () => {
const childRef = useRef<any>(null);
useEffect(() => {
console.log(_.get(childRef, 'current'));
}, [_.get(childRef, 'current')]);
return (
<div>
<RefToGetChild ref={childRef} message={"子組件: say hello"} />
<button onClick={() => {
const child = _.get(childRef, 'current');
const buttonDom = child.buttonRef.current
buttonDom?.click();
}}>父組件: trigger child button</button>
<button onClick={() => {
const child = _.get(childRef, 'current');
child?.onTest();
}}>父組件: 使用子組件的onTest方法</button>
<div>父組件: 子組件的data {JSON.stringify(_.get(childRef, 'current.data'))}</div>
</div>
);
};
export default App;子組件
1) forwardRef作用: 封裝組件, 直接將ref參數(shù)加在props后面(也可以不使用, 自己props定義一下ref需要傳參, 父組件一樣傳ref就行)
2) useImperativeHandle作用和vue3的defineExpose一樣, 存儲需要暴露給父組件讓其獲取的數(shù)據(jù)和函數(shù)
import {
forwardRef,
useEffect,
useImperativeHandle,
useRef,
useState,
} from "react";
const RefToGetChild = forwardRef((props:{message:string;}, ref) => {
const [data, setData] = useState({});
const buttonRef = useRef(null);
useEffect(() => {
setTimeout(() => {
const obj = {
a: 1,
b: 2,
c: 3,
d: Array.from({ length: 10 }, (_, i) => ({ id: i })),
};
setData(obj);
}, 1000);
}, []);
const sayHello = () => {
console.log("hello");
};
const onTest = () => {
console.log('test')
}
useImperativeHandle(ref, () => ({
data,
buttonRef,
onTest,
}));
return (
<div>
<button ref={buttonRef} onClick={sayHello}>
{props.message}
</button>
</div>
);
});
export default RefToGetChild到此這篇關于React通過ref獲取子組件的數(shù)據(jù)和方法的文章就介紹到這了,更多相關React ref獲取子組件內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
React Native之ListView實現(xiàn)九宮格效果的示例
本篇文章主要介紹了React Native之ListView實現(xiàn)九宮格效果的示例,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-08-08

