如何将选择输入的名称设置为等于MenuItem

时间:2018-06-30 23:01:28

标签: reactjs drop-down-menu material-ui

我有一个带有值的选项列表(MenuItem)的“选择输入” 我想要状态中的值,以便稍后可以将它们调度到Redux状态 我设法以正确的格式获取了正确的值 但是现在,选项名称被选中时, 不显示。 如何正确处理事件?

const styles = theme => ({
  button: {
    display: 'block',
    marginTop: theme.spacing.unit * 2,
  },
  formControl: {
    margin: theme.spacing.unit,
    minWidth: 125,
  },
});

class ControlledOpenSelect extends React.Component {
  state = {
    sauce: '',
    saucePrice: 0,
    open: false,
  };

  handleChange = event => {
    const value = event.target.value.split(",")
    this.setState({
      sauce: value[0],
      saucePrice: parseFloat(value[1]),

     });


  };

  handleClose = () => {
    this.setState({ open: false });
  };

  handleOpen = () => {
    this.setState({ open: true });
  };

  render() {
    const { classes } = this.props;
    console.log(this.state );

    return (
      <form autoComplete="off" className='pizzaSauce'>


        <FormControl className={classes.formControl}>
          <InputLabel htmlFor="openSelect">NewAge Sauce</InputLabel>
          <Select
            open={this.state.open}
            onClose={this.handleClose}
            onOpen={this.handleOpen}
            value={this.state.sauce}
            onChange={this.handleChange}
            inputProps={{
              name: 'sauce',
              id: 'openSelect',
            }}
          >
            <MenuItem value="">
              <em>None</em>
            </MenuItem>
            <MenuItem value={'white, 0.50'}>White Sauce &euro;1,00</MenuItem>
            <MenuItem value={'red, 0.50'}>Red Sauce &euro;0,50</MenuItem>
            <MenuItem value={'double, 0.50'}>Double red sauce &euro; 1,00</MenuItem>
            <MenuItem value={'mix, 0.50'}>Mix it up! &euro; 1,50</MenuItem>

          </Select>
        </FormControl>
      </form>
    );
  }
}

ControlledOpenSelect.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(ControlledOpenSelect);

在此之前,handleChange() 看起来像这样

 handleChange = event => {
    this.setState({ [event.target.name]: event.target.value });
  };

1 个答案:

答案 0 :(得分:0)

您的问题是,当没有Select的值为'white'的{​​{1}}时,您尝试为MenuItem的{​​{1}}设置一个值}

不确定是否是最好的选择,但是您可以尝试向状态添加另一个属性,例如'white',并为整个'white, 0.50'设置setState