React?forwardRef?用法案例分析
React.forwardRef 會創(chuàng)建一個React組件,這個組件能夠?qū)⑵浣邮艿?ref 屬性轉(zhuǎn)發(fā)到其組件樹下的另一個組件中。這種技術(shù)并不常見,但在以下兩種場景中特別有用:
- 轉(zhuǎn)發(fā) refs 到 DOM 組件
- 在高階組件中轉(zhuǎn)發(fā) refs
本文重點介紹下React forwardRef 用法。
用法
forwardRef:允許你的組件使用 ref 將一個 DOM 節(jié)點暴露給父組件。
import { forwardRef } from 'react';
const MyInput = forwardRef((props, ref) => {
// ...
});案例分析:ref 屬性是 React 的特殊屬性,不能直接使用。
import {useRef} from 'react'
function InputCom({ref}) {
return (
<input type='text' ref={ref} />
)
}
function App() {
const inpRef = useRef(null)
const focus = () => {
inpRef.current?.focus()
}
return (
<>
<InputCom ref={inpRef} />
</>
)
}上面就會彈出報錯信息:
Warning: InputCom: `ref` is not a prop. Trying to access it will result in `undefined` being returned.
If you need to access the same value Within the child component, you should pass it as a company's prop.
// 警告:InputCom: 'ref不是一個prop。試圖訪問它將導(dǎo)致返回undefine。如果你需要在子組件中訪問相同的值,你應(yīng)該把它作為公司的prop傳遞。
如果想傳遞 ref,這時候就要借助 forwardRef 函數(shù)
import { forwardRef, useRef } from "react";
const InputCom = forwardRef((props, ref) => {
return <input type="text" ref={ref} />;
});
export default function ProRef() {
const inpRef = useRef(null);
const focus = () => {
inpRef.current?.focus();
};
return (
<>
<InputCom ref={inpRef} />
<button onClick={focus}>focus</button>
</>
);
}到此這篇關(guān)于React forwardRef 用法的文章就介紹到這了,更多相關(guān)React forwardRef 用法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
ReactNative支付密碼輸入框?qū)崿F(xiàn)詳解
這篇文章主要為大家介紹了ReactNative支付密碼輸入框?qū)崿F(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-11-11

