【问题标题】:Pass forward ref through Redux Form?通过 Redux Form 传递前向引用?
【发布时间】:2020-01-20 16:06:29
【问题描述】:

我正在使用 Redux 表单:

在父母中:

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" />;
};

我需要从 Parent 管理对 Child 组件的关注。通常你会使用前向引用,但我不确定 Redux Forms 是否可行?以下是错误的,所有的道具都是未定义的:

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

来自控制台的消息:

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

【问题讨论】:

标签: redux-form forward-reference


【解决方案1】:

我使用较旧的语法让它工作,您将 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" />;
};

在 Child 中(不确定这是否需要是一个类):

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

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

【讨论】:

    猜你喜欢
    • 2018-12-31
    • 1970-01-01
    • 1970-01-01
    • 2015-04-24
    • 1970-01-01
    • 2012-08-31
    • 1970-01-01
    相关资源
    最近更新 更多