網(wǎng)站首頁 編程語言 正文
Refs轉(zhuǎn)發(fā)
概述
- 將ref自動(dòng)地通過組件傳遞到子組件的技巧
- 父組件可以通過ref操作子組件,直接使用子組件的DOM
轉(zhuǎn)發(fā)refs到DOM組件
渲染原生 DOM 元素 button 的 FancyButton 組件(子組件)
function FancyButton(props) {
return (
<button className="FancyButton">
{props.children}
</button>
)
}
Ref 轉(zhuǎn)發(fā)是一個(gè)可選特性,其允許某些組件接收 ref,并將其向下傳遞給子組件
//子組件
const FancyButton = React.forwardRef((props, ref) => (
<button ref={ref} className="FancyButton">
{props.children}
</button>
))
//父組件
//可以直接獲取 DOM button 的 ref:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;
//這樣,在父組件中可以直接使用DOM button
以下是對(duì)上述示例發(fā)生情況的逐步解釋:
- 通過調(diào)用 React.createRef 創(chuàng)建了一個(gè) React ref 并將其賦值給 ref 變量
- 指定 ref 為 JSX 屬性,將其向下傳遞給 FancyButton React
- 傳遞ref給forwardRef作為其第二個(gè)參數(shù)
- 向下轉(zhuǎn)發(fā)ref參數(shù)到button,并將其指定為JSX屬性
- 當(dāng)ref掛載完成,ref.current將指向button DOM節(jié)點(diǎn)
組件庫維護(hù)者的注意事項(xiàng)
當(dāng)使用forwardRf時(shí),應(yīng)將其視為一個(gè)新的主版本
在高階組件中轉(zhuǎn)發(fā)refs
轉(zhuǎn)發(fā)ref對(duì)高階組件是很有用的,讓我們從一個(gè)輸出組件props到控制臺(tái)的高階組件為例
function logProps(WrappedComponent) {
class LogProps extends React.Component {
componentDidUpdate(prevProps) {
console.log('old props:', prevProps);
console.log('new props:', this.props);
}
render() {
return <WrappedComponent {...this.props} />;
}
}
return LogProps;
}
logProps組件是一個(gè)高階組件,props將會(huì)傳遞到其包裹的組件。這個(gè)高階組件可以記錄所有傳遞到fancyButton組件的props
class FancyButton extends React.Component {
focus() {
// ...
}
// ...
}
// 我們導(dǎo)出 LogProps,而不是 FancyButton。
// 雖然它也會(huì)渲染一個(gè) FancyButton。
export default logProps(FancyButton)
需要注意:refs 將不會(huì)透傳下去。這是因?yàn)?ref 不是 prop 屬性。就像 key 一樣,其被 React 進(jìn)行了特殊處理
如果對(duì) HOC 添加 ref,該 ref 將引用最外層的容器組件,而不是被包裹的組件
意味著用于我們 FancyButton 組件的 refs 實(shí)際上將被掛載到 LogProps 組件
import FancyButton from './FancyButton';
const ref = React.createRef();
// 我們導(dǎo)入的 FancyButton 組件是高階組件(HOC)LogProps。
// 盡管渲染結(jié)果將是一樣的,
// 但我們的 ref 將指向 LogProps 而不是內(nèi)部的 FancyButton 組件!
// 這意味著我們不能調(diào)用例如 ref.current.focus() 這樣的方法
<FancyButton
label="Click Me"
handleClick={handleClick}
ref={ref}
/>;
解決辦法:可以使用 React.forwardRef API 明確地將 refs 轉(zhuǎn)發(fā)到內(nèi)部的 FancyButton 組件。React.forwardRef 接受一個(gè)渲染函數(shù),其接收 props 和 ref 參數(shù)并返回一個(gè) React 節(jié)點(diǎn)
function logProps(Component) {
class LogProps extends React.Component {
componentDidUpdate(prevProps) {
console.log('old props:', prevProps);
console.log('new props:', this.props);
}
render() {
const {forwardedRef, ...rest} = this.props;
// 將自定義的 prop 屬性 “forwardedRef” 定義為 ref
return <Component ref={forwardedRef} {...rest} />;
}
}
// 注意 React.forwardRef 回調(diào)的第二個(gè)參數(shù) “ref”。
// 我們可以將其作為常規(guī) prop 屬性傳遞給 LogProps,例如 “forwardedRef”
// 然后它就可以被掛載到被 LogProps 包裹的子組件上。
return React.forwardRef((props, ref) => {
return <LogProps {...props} forwardedRef={ref} />;
});
}
在 DevTools 中顯示自定義名稱
下面的組件將在DevTools中顯示為“ForwardRef”
const WrappedComponent = React.forwardRef((props, ref) => {
return <LogProps {...props} forwardedRef={ref} />;
})
如果命名了渲染函數(shù),DevTools 也將包含其名稱(例如 “ForwardRef(myFunction)”)
const WrappedComponent = React.forwardRef(
function myFunction(props, ref) {
return <LogProps {...props} forwardedRef={ref} />;
}
)
設(shè)置函數(shù)的 displayName 屬性來包含被包裹組件的名稱
function logProps(Component) {
class LogProps extends React.Component {
// ...
}
function forwardRef(props, ref) {
return <LogProps {...props} forwardedRef={ref} />;
}
// 在 DevTools 中為該組件提供一個(gè)更有用的顯示名。
// 例如 “ForwardRef(logProps(MyComponent))”
const name = Component.displayName || Component.name;
forwardRef.displayName = `logProps(${name})`;
return React.forwardRef(forwardRef);
}
原文鏈接:https://blog.csdn.net/xbczrz/article/details/128083925
相關(guān)推薦
- 2022-05-12 Kotlin map 高級(jí)函數(shù)返回新的集合
- 2023-10-28 如何給k8s集群里的資源打標(biāo)簽_云其它
- 2022-11-19 C#字符串與正則表達(dá)式的圖文詳解_C#教程
- 2022-09-28 Dephi逆向工具Dede導(dǎo)出函數(shù)名MAP導(dǎo)入到IDA中的實(shí)現(xiàn)方法_python
- 2022-09-02 pytest使用@pytest.mark.parametrize()實(shí)現(xiàn)參數(shù)化的示例代碼_pytho
- 2022-04-18 ASP.Net?Core?MVC基礎(chǔ)系列之獲取配置信息_基礎(chǔ)應(yīng)用
- 2023-07-13 自定義設(shè)置echarts label里的顏色
- 2022-07-09 flutter封裝單選點(diǎn)擊菜單工具欄組件_Android
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支