0

我基于redux-form-material-ui repo的官方示例。我的代码如下所示:

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". 它没有被更深地传递。

我将不胜感激任何想法如何解决它。

4

1 回答 1

2
  1. 你不需要制作你ref的道具,因为它是你的组件本地的。ref="field"如果您愿意,您可以直接调用它。虽然这可能不是你的问题。
  2. 此外,您还不如一直路过withRef

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

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

这有帮助吗?

于 2016-07-07T13:31:28.097 回答