首页 > 解决方案 > React Redux Material-UI 自动完成

问题描述

使用 redux-form 时,我正在努力从 Material-ui 自动完成中获取价值。有没有人解决这个问题?我正在使用 material-ui 自动完成https://material-ui.com/components/autocomplete/中的确切示例 我能够看到列表选项并在单击两次后填充,但我无法提取真实的值,而不是我返回 ({ title : 0 })而不是值。

import React from "react";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";
import { Field, reduxForm } from "redux-form";
import { connect } from "react-redux";

class Form extends React.Component {
  onSubmit = formValues => {
    console.log(formValues);
  };

  renderTextField = ({
    label,
    input,
    meta: { touched, invalid, error },
    ...custom
  }) => (
    <Autocomplete
      label={label}
      options={this.props.movies}
      placeholder={label}
      getOptionLabel={option => option.title}
      onChange={input.onChange}
      {...input}
      {...custom}
      renderInput={params => (
        <TextField {...params} label={label} variant="outlined" fullWidth />
      )}
    />
  );

  render() {
    const { handleSubmit } = this.props;

    return (
      <div>
        <form onSubmit={handleSubmit(this.onSubmit)}>
          <Field
            name="propertySelector"
            component={this.renderTextField}
            label="Select Property"
            type="text"
          />
        </form>
      </div>
    );
  }
}
const mapStateToProps = state => {
  console.log(state);
  return {
    movies: [
      { title: "The Shawshank Redemption", year: 1994 },
      { title: "The Godfather", year: 1972 },
      { title: "Schindler's List", year: 1993 }
    ]
  };
};

Form = reduxForm({
  form: "auto_complete"
});

export default connect(mapStateToProps, null)(Form);

标签: react-reduxmaterial-uiredux-form

解决方案


通过将 (event, value) 传递给 onChange 道具来解决。

onChange={(event, value) => console.log(value)}

来自文档;

Callback fired when the value changes.

Signature:
function(event: object, value: T) => void
event: The event source of the callback.
value: null


推荐阅读