【问题标题】:setValue from material UI selectsetValue 从材质 UI 选择
【发布时间】:2021-09-06 05:43:47
【问题描述】:

我创建了一个下拉菜单

  const [splittingMethod, setSplittingMethod] = useState('');

  const handleChange = (e: any) => {
    //setSplittingMethod(e)
    console.log('value', splittingMethod)

  }
....

  <FormControl variant="filled" >
            <InputLabel id="demo-simple-select-filled-label" className={classes.field}>Splitting Method</InputLabel>
            <Select
              labelId="demo-simple-select-filled-label"
              id="demo-simple-select-filled"
              value={splittingMethod}
              onChange={(e)=>handleChange(e)}
            >
              <MenuItem value="random">
                Random
              </MenuItem>
              <MenuItem value={'timeEnd'}>Time End</MenuItem>
              <MenuItem value={'slidingWindow'}>Sliding Window</MenuItem>
            </Select>
          </FormControl>

我想将所选项目的值保存到splittingMethod 变量中。我怎样才能做到这一点?我目前的方法会给我一个错误:

react-dom.development.js:13231 Uncaught Error: Objects are not valid as a React child

【问题讨论】:

    标签: javascript reactjs typescript react-hooks material-ui


    【解决方案1】:

    您必须访问e.target.value 才能获得价值

    import React, { useState } from "react";
    import { FormControl, InputLabel, Select, MenuItem } from "@material-ui/core";
    const App = () => {
      const [splittingMethod, setSplittingMethod] = useState("");
    
      const handleChange = (
        e: React.ChangeEvent<{
          name?: string | undefined;
          value: unknown;
        }>
      ) => {
        // type checking
        const value = typeof e.target.value === "string" ? e.target.value : "";
    
        setSplittingMethod(value);
      };
      return (
        <FormControl variant="filled" style={{ width: "100%" }}>
          <InputLabel
            id="demo-simple-select-filled-label"
            style={{ width: "100%" }}
          >
            Splitting Method
          </InputLabel>
          <Select
            labelId="demo-simple-select-filled-label"
            id="demo-simple-select-filled"
            value={splittingMethod}
            onChange={handleChange}
          >
            <MenuItem value="random">Random</MenuItem>
            <MenuItem value={"timeEnd"}>Time End</MenuItem>
            <MenuItem value={"slidingWindow"}>Sliding Window</MenuItem>
          </Select>
        </FormControl>
      );
    };
    
    export default App;
    
    

    现场演示

    【讨论】:

      猜你喜欢
      • 2020-11-26
      • 2017-11-15
      • 2020-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-27
      • 1970-01-01
      相关资源
      最近更新 更多