欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

記錄React使用connect后,ref.current為null問題及解決

 更新時(shí)間:2023年05月12日 09:41:47   作者:草率小猿  
記錄React使用connect后,ref.current為null問題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

問題

在用React開發(fā)項(xiàng)目的過程中,遇到一個(gè)問題,使用connect連接低階組件包裝成高階組件HOC后,父組件通用ref調(diào)用子組件方法時(shí),提示xxxRef.current為null的錯(cuò)誤。

代碼如下:

// 子組件
// 通過connect方式連接為高階組件
export default connect(
? ? mapStateToProps,
)(ComboSelectorForm);
// 父組件
constructor(props: IComboSelectorListProps | Readonly<IComboSelectorListProps>) {
? ? super(props);
? ? // ...
? ? this.formRef = React.createRef();
? ? // ...
}
// 組件掛載在formRef上
<ComboSelectorForm
? ? ref={this.formRef}
? ? id={this.state.id}
? ? onSaveSuccess={this.handleSaveSuccess}
>
</ComboSelectorForm>
// 調(diào)用子組件方法
this.formRef.current.methodName();

父組件調(diào)用子組件方法后,報(bào)以下錯(cuò)誤

TypeError: Cannot read properties of null (reading 'methodName')

解析

React的高階組件HOC,可以理解成在低階組件上進(jìn)行一些封裝。

高階組件HOC如果不做一些特殊處理,是無法直接訪問低階組件實(shí)例的,要想通過ref訪問低階組件實(shí)例,調(diào)用connect時(shí),需要傳遞參數(shù){forwardRef : true}。

connect方法有四個(gè)參數(shù),官方文檔是這樣說明的:

  • mapStateToProps?: Function
  • mapDispatchToProps?: Function | Object
  • mergeProps?: Function
  • options?: Object

對(duì)于前面三個(gè)參數(shù)先不展開來講解,主要第四個(gè)options參數(shù),有以下幾個(gè)屬性:

{
? context?: Object,
? pure?: boolean,
? areStatesEqual?: Function,
? areOwnPropsEqual?: Function,
? areStatePropsEqual?: Function,
? areMergedPropsEqual?: Function,
? forwardRef?: boolean,
}

其中最后一個(gè)參數(shù)forwardRef正是我們的主角,官方文檔里這樣解釋:

If {forwardRef : true} has been passed to connect, adding a ref to the connected wrapper component will actually return the instance of the wrapped component.

當(dāng)該參數(shù)forwardRef設(shè)置為true時(shí),包裹組件(wrapper component )的ref屬性將會(huì)實(shí)際返回被包裹組件(wrapped component)實(shí)例。

OS:原諒我翻譯水平有限。(>_<)

最終解決方案

直接上代碼:

// 子組件
// 通過connect方式連接為高階組件
export default connect(
? ? mapStateToProps,
? ? null,?? ?// 新加參數(shù)
? ? null,?? ?// 新加參數(shù)
? ? { forwardRef: true }?? ?// 新加參數(shù)
)(ComboSelectorForm);
// 父組件,與之前代碼一致
constructor(props: IComboSelectorListProps | Readonly<IComboSelectorListProps>) {
? ? super(props);
? ? // ...
? ? this.formRef = React.createRef();
? ? // ...
}
// 組件掛載在formRef上
<ComboSelectorForm
? ? ref={this.formRef}
? ? id={this.state.id}
? ? onSaveSuccess={this.handleSaveSuccess}
>
</ComboSelectorForm>
// 調(diào)用子組件方法
this.formRef.current.methodName();

通過以上改造后,父組件能夠正常訪問ref實(shí)例。

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論