为什么不能在select中选择选项?

时间:2018-10-31 08:02:42

标签: javascript reactjs material-ui

我正在尝试连接库material ui中的select。我不知道为什么不能选择option并在state中输出?有人遇到这样的问题吗?

详细的代码示例here

import React from "react";
import ReactDOM from "react-dom";
import Select from "@material-ui/core/Select/Select";
import InputLabel from "@material-ui/core/InputLabel/InputLabel";
import FormControl from "@material-ui/core/FormControl/FormControl";
import MenuItem from "@material-ui/core/MenuItem/MenuItem";

class App extends React.Component {
  state = {
    age: "",
    name: "hai"
  };
  handleChange = event => {
    this.setState({ [event.target.name]: event.target.valueSelect });
  };
  render() {
    return (
      <div className="App">
        <FormControl style={{ width: "100%", marginTop: "27px" }}>
          <InputLabel htmlFor="age-auto-width">Title</InputLabel>
          <Select
            value={this.state.age}
            onChange={this.handleChange}
            inputProps={{
              name: "hai",
              id: "age-simple"
            }}
          >
            <MenuItem value={10}>Ten</MenuItem>
            <MenuItem value={20}>Twenty</MenuItem>
            <MenuItem value={30}>Thirty</MenuItem>
          </Select>
        </FormControl>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

2 个答案:

答案 0 :(得分:2)

没有event.target.valueSelect。使用event.target.value。这是sandbox

答案 1 :(得分:1)

在您的代码中:this.setState({ [event.target.name]: event.target.valueSelect });

将其更改为event.taget.value

这来自您选择的值value={this.state.age} ...

通常...清理起来看起来像这样:

class App extends React.Component {
  state = { age: "" };

  handleChange = event => {
    this.setState({ [event.target.name]: event.target.value });
  };
  render() {
    return (
      <div className="App">
        <FormControl style={{ width: "100%", marginTop: "27px" }}>
          <InputLabel htmlFor="age-auto-width">Title</InputLabel>
          <Select
            value={this.state.age}
            onChange={this.handleChange}
            inputProps={{
              name: "age"
            }}
          >
            <MenuItem value={10}>Ten</MenuItem>
            <MenuItem value={20}>Twenty</MenuItem>
            <MenuItem value={30}>Thirty</MenuItem>
          </Select>
        </FormControl>
      </div>
    );
  }
}