高階組件
? ? ? ? 參考文檔:高階組件 – React (reactjs.org)
????????高階組件(Higher-Order Components,簡稱?HOC)是React中用于復(fù)用組件邏輯的一種高級技巧。具體而言:高階組件是參數(shù)為組件,返回值為新組件的函數(shù)。
????????組件是將 props 轉(zhuǎn)換為 UI,而高階組件是將組件轉(zhuǎn)換為另一個組件。
????????HOC 在 React 的第三方庫中很常見,例如 Redux 的?connect?和 Relay 的?createFragmentContainer。
? ? ? ? 此處不再搬運(yùn)高階組件具體如何使用的部分,詳情參考React官網(wǎng)文檔即可。
ref轉(zhuǎn)發(fā):forwardRef
? ? ? ? forwardRef函數(shù)的作用,
forwardRef
允許組件使用 ref 將 DOM 節(jié)點暴露給父組件。
? ? ? ? 簡單講:就是讓子級函數(shù)式組件除了props參數(shù)之外,額外擁有第二個參數(shù)ref;之后就可以在父組件中拿到這個ref,從而去調(diào)用子組件中暴露出來的方法。
import { forwardRef } from 'react';
const MyInput = forwardRef(function MyInput(props, ref) {
// ...
});
? ? ? ? 然后在父組件中,可以定義ref屬性,來拿到子組件的引用,偽代碼示例如下,
//這里是父組件
export default ()=>{
const myInputRef = useRef();
//調(diào)用方式:
//myInputRef.current.doXXX();
return (<MyInput ref={myInputRef}/>);
}
?暴露句柄:useImperativeHandle
? ? ? ? 那么,通過forwardRef轉(zhuǎn)發(fā)給子組件的ref所調(diào)用的具體方法/句柄如何定義呢?
useImperativeHandle
是 React 中的一個 Hook,它能讓你自定義由 ref 暴露出來的句柄。useImperativeHandle(ref, createHandle, dependencies?)文章來源:http://www.zghlxwxcb.cn/news/detail-833815.html
? ? ? ? 例如:以下代碼就為MyInput組件提供了doSomething句柄,供父組件通過ref來調(diào)用,文章來源地址http://www.zghlxwxcb.cn/news/detail-833815.html
import { forwardRef, useImperativeHandle } from 'react';
const MyInput = forwardRef(function MyInput(props, ref) {
useImperativeHandle(ref, () => {
return {
//向外暴露的句柄
doSomething:() =>{
console.log('here is children method!');
return 'do-something'
},
};
}, []);
return <input {...props} />;
});
完整示例代碼
子組件:MyInput
import { forwardRef, useImperativeHandle } from 'react';
const MyInput = forwardRef(function MyInput(props, ref) {
useImperativeHandle(ref, () => {
return {
//向外暴露的句柄
doSomething:() =>{
console.log('here is children method!');
return 'do-something'
},
};
}, []);
return <input {...props} />;
});
父組件
//這里是父組件
export default ()=>{
const myInputRef = useRef();
//調(diào)用方式:
//myInputRef.current.doXXX();
const clickHandler = ()=>{
myInputRef.current.doSomething(/*params*/);
}
return (<>
<MyInput ref={myInputRef}/>
<button onClick={clickHandler}>click here</button>
</>);
}
到了這里,關(guān)于React:高階組件|ref轉(zhuǎn)發(fā)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!