redux-form-material-ui使用getRenderedComponent()总是抛出一个错误

时间:2016-07-06 12:18:16

标签: reactjs redux material-ui redux-form

我基于 redux-form-material-ui repo的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}
      />
    );
  }
}

我正在传递focuswithRef属性,仅用于第一个有错误的字段。在此字段中,我总是收到错误:Uncaught (in promise) Error: If you want to access getRenderedComponent(), you must specify a withRef prop to Field(…)

我可以看到refwithRef都传递给Field。然后在包含ref="wrappedInstance"的组件中,我仍然可以看到withRef="true"。它不会更深入。

我很感激如何解决它。

1 个答案:

答案 0 :(得分:2)

  1. 您无需将ref作为道具,因为它属于您的组件的本地。如果您愿意,可以将其称为ref="field"。虽然这可能不是你的问题。
  2. 另外,你也可以一直传递withRef
  3. focus()道具从focus更改为false时,您似乎想要致电true。为此,你应该做的事情如下:

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

    这有帮助吗?