具有Redux表单的物料UI自动完成组件

时间:2020-02-13 03:45:02

标签: javascript reactjs autocomplete material-ui redux-form

问题如下: 我在Redux表单中使用Material Ui自动完成组件(https://material-ui.com/api/autocomplete/)。 自动完成组件提供了一个选项列表,其中每个选项都是一个对象,包含“ @id”属性和一些其他人类可读属性,具体取决于资源。

通过“ getOptionLabel”道具告知组件从可读属性生成选项标签。在从自动完成功能提供的列表中键入/选择任何标签后,该标签将转换为输入值,并因此作为redux-form字段的值存储在商店中。

问题:自动填充组件应提供的Redux表单的值与标签上显示的值不同。 但是到目前为止,我还无法以某种简单的方式来做到这一点。我确定它是有可能的,但是在这一点上,我还不确定我不知道哪种组件道具组合可以处理这种情况。

到目前为止,我设法在表单本身上使用ChildContextTypes,以将redux表单更改分派(https://redux-form.com/8.2.2/docs/api/actioncreators.md/#-code-change-form-string-field-string-value-any-code-)传递给Autocomplete组件。 这样,我可以在自动完成组件中指定一个onChange事件,该事件将处理值的切换。

当前代码:

export class AutocompleteField extends React.Component {
  constructor(props, context) {
        super(props);

        this.state = {
            options: [],
            selectedValue: null,
        };
    }
  static contextTypes = {
        changeFieldValue: PropTypes.func.isRequired
    };
  componentDidMount() {
        this.fetchLabels();
    }
  fetchLabels() {
       // call api, setState({options: resulst of api call })
    }
  componentDidUpdate(prevProps, prevState, snapshot) {
        if (!this.state.selectedValue) {
            return;
        }
        this.context.changeFieldValue(`example_field`, `${this.state.selectedValue["@id"]}`);
    }
  changeLabelToIRI(event, value) {
        this.setState({selectedValue: value})
    }
  getOptionsLabels(option) {
    // format option labels according to resource
  }
  render() {
      const {input} = this.props;
      return(
        <Autocomplete
                    options={this.state.options}
                    getOptionLabel={option => (this.getOptionLabels(option))}
                    onChange={(event, value ) => this.changeLabelToIRI(event, value)}
                    renderInput={params => (
                        <TextField
                            {...params}
                            {...input}
                        />
                    )}
                />
      )
  }
}

真的可以使用一些技巧来简化它。

0 个答案:

没有答案