javascript - 在高阶组件中使用 ref
问题描述
我有一个想要附加的Table
组件。ref
使用:Table.js
class Table extends React.Component {
constructor(props) {
super(props);
this.state = {
rows: 1,
dataLength: props.dataLength,
}
this.tableRef = React.createRef();
}
componentDidUpdate() {
//using ref
this.tableRef.current ..... //logic using ref
this.state.rows ..... //some logic
}
render() {
<TableContainer ref={this.tableRef} />
<CustomPagination />
}
}
这工作正常,但现在我的要求已经改变,我想重用 Table 组件,并将分页应用于我的应用程序中的所有表格。我决定做一个 HOC withCustomPagination
。
使用:withCustomPagination.js HOC
import CustomPagination from 'path/to/file';
const withCustomPagination = tableRef => Component => {
return class WithCustomPagination extends React.Component {
constructor(props) {
super(props);
this.state = {
rows: 1,
dataLength: props.dataLength,
}
}
componentDidUpdate() {
tableRef.current.state ..... //logic using ref, Error for this line
this.state.rows ..... //some logic
}
render() {
return (
<Component {...state} />
<CustomPagination />
)
}
}
}
export default withCustomPagination;
新的Table.js:
import withCustomPagination from '/path/to/file';
const ref = React.createRef();
const Table = props => (
<TableContainer ref={ref} />
);
const WrappedTable = withCustomPagination(ref)(Table);
HOCwithCustomPagination
返回一个类,该类WithCustomPagination
具有componentDidUpdate
在逻辑中使用 Table ref 的生命周期方法。所以我尝试将ref
在Table.js中创建的作为参数传递给withCustomPagination
,即 curried withref
和Table
stateless 组件。
这种使用ref
是错误的,我得到错误:TypeError: Cannot read property 'state' of null
。
我尝试使用Forwarding Refs,但无法实现。
如何将表格传递ref
给withCustomPagination
HOC 并能够在 HOC 中使用它?
解决方案
在这种情况下,您可以使用useImperativeHandle
这意味着您必须转发ref
并指定要ref
在功能组件内共享的函数或对象,或者...。
这是我的临时示例:
import React from 'react';
import { View } from 'react-native';
export function CommonHoc(WrappedComponent) {
const component = class extends React.Component {
componentDidMount() {
this.refs.myComponent.showAlert();
}
render() {
return (
<>
<WrappedComponent
ref='myComponent'
{...this.state}
{...this.props}
/>
</>
);
}
};
return component;
}
这是我的无状态组件
const HomeController=(props,ref)=> {
useImperativeHandle(ref, () => ({
showAlert() {
alert("called");
},
}));
return (
<Text>home</Text>
);
};
export default CommonHoc(forwardRef(HomeController));
推荐阅读
- python - 使用 Python 获取目录中文件列表的修改日期的最快方法是什么?
- wordpress - WordPress 将帖子保存在错误的时区
- python - 如何将 PyLaTeX 中的希腊字母编译成表格?
- vue.js - Bootstrap-Vue + Vuelidate:用于创建和更新数据的“对话框”
- reactjs - 使用 in react 在 tailwindcss 中获取额外不需要的空格
- python-3.x - python在哪里发送没有目录路径的文件?
- flutter - Flutter InappWebView canGoBack - 找不到方法的实现
- python-3.x - 我得到一个错误,但我没有找到它(Python)
- sql - (+) 运算符用于 join ,但很奇怪
- python - Pandas:使用 plotly 作为后端时如何选择绘图元素颜色?