从Material-UI选择组件中的元素列表中预选择一个元素

时间:2019-11-15 11:25:43

标签: reactjs material-ui

我想预选列表ID为3的元素。如果我不提供预选元素,则应自动显示禁用的项目。当前,选择框仅显示选择您的选项,如果我尝试传递 alreadySelected ,则该列表不起作用,以后也无法更改我的选项。

我的应用程序组件:

import React from "react";
import ReactDOM from "react-dom";

import CustomSelect from "./components/Select";

function App() {
  const [selectElement, setSelectElement] = React.useState(0);

  // This element should be passed somehow down to the select component
  const alreadySelected = 3;

  return (
    <div className="App">
      <CustomSelect
        selectElement={selectElement}
        setSelectElement={setSelectElement}
      />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

我的选择组件:

import React from "react";
import * as PropTypes from "prop-types";
import { FormControl, InputLabel, MenuItem, Select } from "@material-ui/core";

function CustomSelect(props) {
  const { selectElement, setSelectElement } = props;

  const list = [
    {
      id: 1,
      name: "test 1"
    },
    {
      id: 2,
      name: "test 2"
    },
    {
      id: 3,
      name: "test 3"
    }
  ];

  function handleChange(event) {
    setSelectElement(event.target.value);
  }

  return (
    <FormControl fullWidth>
      <InputLabel htmlFor="qualification-type">Select box</InputLabel>
      <Select value={selectElement} onChange={handleChange}>
        <MenuItem disabled value={0}>
          <em>Choose your option</em>
        </MenuItem>
        {list.map(item => (
          <MenuItem key={`type-${item.id}`} value={item.id}>
            {item.name}
          </MenuItem>
        ))}
      </Select>
    </FormControl>
  );
}

CustomSelect.propTypes = {
  selectElement: PropTypes.number.isRequired,
  SetSelectElement: PropTypes.func.isRequired
};

export default CustomSelect;

1 个答案:

答案 0 :(得分:0)

useState挂钩接受默认值作为参数。您默认设置为0。相反:

使用您的状态默认值作为3: const [selectElement, setSelectElement] = React.useState(3);

Yiu甚至可以动态导出并作为默认值传递给状态。让我知道。