我基于 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}
/>
);
}
}
我正在传递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"
。它不会更深入。
我很感激如何解决它。
答案 0 :(得分:2)
ref
作为道具,因为它属于您的组件的本地。如果您愿意,可以将其称为ref="field"
。虽然这可能不是你的问题。withRef
。当focus()
道具从focus
更改为false
时,您似乎想要致电true
。为此,你应该做的事情如下:
componentWillUpdate(nextProps) {
if (!this.props.focus && nextProps.focus) {
this.refs.field
.getRenderedComponent()
.getRenderedComponent()
.focus()
}
}
这有帮助吗?