Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

reactjs - Get value of Material-UI Select within form

I am trying to get the currently selected value of a Material-UI Select component within form component, but I can't figure out what the proper way is, here is what I have tried:

<form onSubmit={handleCreateNewItem}>
  <TextField id="name" label="Name" />
  ...more text fields...
  <Select id="typeOfQuantity">
    {typesOfQuantities.map((menuItem) => (
      <MenuItem value={menuItem}>{menuItem}</MenuItem>
    ))}
  </Select>

  <IconButton type="submit">
    <DoneIcon />
    <Typography variant="h6" gutterBottom>
      Add
    </Typography>
  </IconButton>
</form>

And the handleCreateNewItem:

const handleCreateNewItem = (e) => {
  e.preventDefault();
  const { name, typeOfQuantity, ...restOfFormFields} = e.target.elements;

  console.log(typeOfQuantity);
};

But typeOfQuantity is undefined. I am not using a separate onChange, because there are multiple fields on the form.

Do I have to create its own separate onChange handler and keep its reference? It would probably work, but it seems like a bad way to do it...

I have just tried with a pure html form and select and it works without issues:

const handleCreateNewItem = (e) => {
  e.preventDefault();
  const { name, typeOfQuantity, ...restOfFields } = e.target.elements;

  console.log(name.value);
  console.log(typeOfQuantity.value);
};

<form onSubmit={handleCreateNewItem}>
  <select id="typeOfQuantity">
    {typesOfQuantities.map((menuItem) => (
      <option value={menuItem}>{menuItem}</option>
    ))}
  </select>
</form>
question from:https://stackoverflow.com/questions/65652339/get-value-of-material-ui-select-within-form

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use onChange. Then set the value, which will then be capturable in your form.

const [ value, setValue ] = useState('');


    const handleCreateNewItem = (e) => {
      e.preventDefault();
      setValue(e.target.value)
    };

    <FormControl className={classes.formControl}>
        <InputLabel id="demo-simple-select-label">Age</InputLabel>
        <Select
          labelId="demo-simple-select-label"
          id="demo-simple-select"
          value={age}
          onChange={handleCreateNewItem}
        >
          <MenuItem value={10}>Ten</MenuItem>
          <MenuItem value={20}>Twenty</MenuItem>
          <MenuItem value={30}>Thirty</MenuItem>
        </Select>
      </FormControl>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...