【问题标题】:redux-form-material-ui using getRenderedComponent() throws always an errorredux-form-material-ui 使用 getRenderedComponent() 总是抛出错误
【发布时间】:2016-07-06 12:18:16
【问题描述】:

我基于来自 redux-form-material-ui 存储库的 official example。我的代码如下所示:

import React from 'react';
import { Field } from 'redux-form';
import { TextField } from 'redux-form-material-ui';

export default class FormTextField extends React.Component {

  constructor(props) {
    super(props);
  }

  componentWillUpdate(nextProps) {
    const { name, withRef, focus } = nextProps;
    if (withRef && focus) {
      this.refs[name]
        .getRenderedComponent()
        .getRenderedComponent()
        .focus();
    }
  }

  render() {
    const { name, label, errorText, withRef } = this.props;

    return (
      <Field
        name={name}
        component={TextField}
        hintText={label}
        floatingLabelText={label}
        errorText={errorText}
        ref={name}
        withRef={withRef}
      />
    );
  }
}

我仅将 focus 和 withRef 属性传递给有错误的第一个字段。在这个领域我总是得到一个错误:Uncaught (in promise) Error: If you want to access getRenderedComponent(), you must specify a withRef prop to Field(…)

我能够看到ref 和withRef 都传递给Field。然后在带有ref="wrappedInstance" 的组件中我仍然可以看到withRef="true"。它没有被更深地传递。

如果有任何解决方法的想法,我将不胜感激。

【问题讨论】:

    标签: reactjs redux material-ui redux-form


    【解决方案1】:
    1. 您不必将ref 设为道具,因为它在您的组件中是本地的。如果您愿意,您可以将其称为ref="field"。虽然这可能不是你的问题。
    2. 另外,您不妨一直传递withRef。

    当focus 属性从false 更改为true 时,听起来您想调用focus()。为此,您应该执行以下操作:

    componentWillUpdate(nextProps) {
      if (!this.props.focus && nextProps.focus) {
        this.refs.field
          .getRenderedComponent()
          .getRenderedComponent()
          .focus()
      }
    }
    

    这有帮助吗?

    【讨论】:

      猜你喜欢
      • 2018-09-14
      • 1970-01-01
      • 1970-01-01
      • 2020-11-03
      • 2018-10-21
      • 2017-07-23
      • 1970-01-01
      • 2017-11-29
      • 2019-04-24
      相关资源
      最近更新 更多