通过 Redux 表单传递转发引用?



我正在使用Redux Forms:

在父级中:

class Parent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
componentDidMount() {
console.log(this.myRef);
}
render() {
return (
<div>   
<CustomField ref={this.ref} />
</div>
)
}

在自定义字段中:

import { Field } from 'redux-form';
import Child from 'components/Child';
const CustomField = props => {
return <Field {...props} component={Child} type="text" />;
};

我需要从父级管理对子组件的关注。通常您会使用转发引用,但我不确定这是否适用于 Redux 表单?以下是错误,所有道具都是未定义的:

const CustomField = React.forwardRef((props, ref) => {
return <Field {...props} component={() => <Child {...props} ref={ref} />} type="text" />;
});

来自控制台的消息:

警告:道具类型失败:提供给字段的道具组件无效。

我使用较旧的语法让它工作,您将 ref 作为普通道具传递。我认为你必须称它为ref以外的其他东西:

在父级中:

class Parent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
componentDidMount() {
console.log(this.myRef);
}
render() {
return (
<div>   
<CustomField customRef={this.ref} />
</div>
)
}

在自定义字段中:

import { Field } from 'redux-form';
import Child from 'components/Child';
const CustomField = props => {
return <Field {...props} component={Child} type="text" />;
};

在孩子中(不确定这是否需要是一个类(:

class Child Extends React.Component {
render(){
return(
<input ref={customRef}  />
)
}
}

对我来说,旧样式似乎更容易使用。作为一个切线点,如果有人可以解释它的缺点,那会很有趣,因为我认为有一些?

最新更新