【问题标题】:How to use option value in React Select如何在 React Select 中使用选项值
【发布时间】:2021-06-14 08:53:04
【问题描述】:

我正在学习 react,这很有趣!

我正在使用 react-select 在 React 中创建一个注册表单。

我正在映射数组中的值:

const options = [ 'female', 'male', 'other']

<Select {...register("gender")} 
          label="Gender"
          fullWidth 
          variant="outlined"
          >
      {options.map(value => (
        <option key={value} value={value}>
          {value}
        </option>
      ))}
      </Select>

但我收到以下警告:

警告:使用 defaultValuevalue 属性,而不是设置 selected

问题:

  1. 如何使用defaultValuevalue 道具?
  2. 我设置了 label="Gender" 但不可见,为什么?

【问题讨论】:

    标签: reactjs react-hooks react-select


    【解决方案1】:
    const options = [
      { value: "female", label: "Female" },
      { value: "male", label: "Male" },
      { value: "other", label: "Other" }
    ];
    
    export default function App() {
      const [gender, setGender] = useState("");
    
      const handleChange = (event) => {
        setGender(event.target.value);
      };
    
      return (
        <div className="App">
          <Select
            value={gender}
            onChange={handleChange}
          >
            {options.map((option) => (
              <MenuItem key={option.value} value={option.value}>
                {option.label}
              </MenuItem>
            ))}
          </Select>
        </div>
      );
    }
    

    API 参考:https://material-ui.com/api/select/

    工作演示:https://codesandbox.io/s/pedantic-jones-dyfwd?file=/src/App.js:119-788

    【讨论】:

    • 类型'{选项:{值:字符串;标签:字符串; }[]; }' 不可分配给类型 'IntrinsicAttributes & SelectProps'。类型“IntrinsicAttributes & SelectProps”.ts(2322) 上不存在属性“选项”
    • 感谢您的解决方案,但我正在使用材质 UI 库。从“@material-ui/core”中选择;使用 react-select 会弄乱我的组件——不同的设计。我不确定这个问题是否可以通过@material-ui/core 解决
    • @mariaaustsen 看到我更新的答案。您的标签声明了 react-select,所以我假设您正在使用该库。我现在已经改成 Material UI 解决方案了。
    • 谢谢!我标记 react-select 的错误。现在可以了。根据这个,我也有关于切换材质 ui 的问题:stackoverflow.com/questions/67989547/…
    猜你喜欢
    • 1970-01-01
    • 2015-04-21
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    • 2020-01-01
    • 2020-06-22
    • 2018-10-30
    • 2020-02-15
    相关资源
    最近更新 更多