Material-ui的选择器对我不起作用?

时间:2018-07-17 13:45:09

标签: javascript reactjs material-ui

我尝试实现material-ui selector的示例,并从github example获得了代码片段

import React from "react";
import {withStyles} from "material-ui/styles";
import Select from "material-ui/Select";
import styles from "../../overtimesStyles";

class DivisionReport extends React.Component {
  state = {
    selectedOption: "",
  }

  handleChange = (selectedOption) => {
    this.setState({selectedOption});
    // selectedOption can be null when the `x` (close) button is clicked
    if (selectedOption) {
      console.log(`Selected: ${selectedOption.label}`);
    }
  }

  render() {
    const {selectedOption} = this.state;

    return (
      <Select
        name="form-field-name"
        value={selectedOption}
        onChange={this.handleChange}
        options={[
         {value: "one", label: "One"},
         {value: "two", label: "Two"},
         {value: "333", label: "One"},
         {value: "444", label: "444"},
         {value: "555", label: "555"},
         {value: "666", label: "666"},
        ]}
      />
    );
  }
}

export default withStyles(styles)(DivisionReport);

但是我没有看到可供选择的项目: enter image description here

您能建议我为什么遇到这个问题吗?

p.s。使用DivisionReport的顶级组件是:

const OvertimesReport = ({handleChangeSelection, selectedOption, classes}) => (
  <div className={classes.workarea}>
    <Card>
      <CardContent className="overtimes">
        <DivisionReport handleChangeSelection={handleChangeSelection} selectedOption={selectedOption}/>
      </CardContent>
    </Card>
  </div>
);

样式是:

workarea: {
  margin: "0px 5%",
},

2 个答案:

答案 0 :(得分:1)

您正尝试从Select导入material-ui/Select组件,但是如果从react-select包中导入,则应该导入:

import Select from "react-select";

还请注意,option的值键名为value,标签键名为label,而不是valueKeylabelKey

<Select
  name="form-field-name"
  value={selectedOption}
  onChange={this.handleChange}
  options={[
    {value: "one", label: "One"},
    {value: "two", label: "Two"},
    {value: "333", label: "One"},
    {value: "444", label: "444"},
    {value: "555", label: "555"},
    {value: "666", label: "666"},
   ]
  }
/>

答案 1 :(得分:0)

import Select from '@material-ui/core/Select';

然后在渲染器中

   <Select
      native
      name="form-field-name"
      value={selectedOption}
      onChange={this.handleChange}
   >
     <option key="1" value="1"> 1 </option>
     <option key="2" value="2"> 2 </option> 
     <option key="3" value="3"> 3 </option>  

   </Select>

尝试这种方式,让我知道它的工作原理