简体   繁体   English

获取选项 Material-UI React 中选择的第一个元素

[英]get first element selected in options Material-UI React

Hello guys I'm using React Material UI select.大家好,我正在使用 React Material UI select。 When I change option I trigger onChange method and add attr on selected value so how can I set fisrt option of items as selected.当我更改选项时,我会触发 onChange 方法并在所选值上添加 attr,那么我如何将项目的第一个选项设置为选中状态。

       value={} **// I want to display first option to selected without trigger on Change method**
       onChange={(e) => {
            data.forEach(a => {
            if (a.Id === e.target.value) {
                 a.selected = true
               } else {
                 a.selected = false
               }
            });
       }}
     >
         <MenuItem disabled value=""><em>Please Select</em></MenuItem>
         {data.map((item) => {
               return (
                 <MenuItem key={item.Id} value={item.Id} >
                       {item.Ad}
                 </MenuItem>
               );
         })}
     </Select>

You need 2 states on your component, data and active .您的组件需要 2 个状态,即dataactive Where data is the items you want to display on the dropdown, and active which indicates what item is currently selected.其中data是您要在下拉列表中显示的项目,而active表示当前选择的项目。 Commonly, we use useEffect hook to initialize states.通常,我们使用useEffect挂钩来初始化状态。

Also, wehave to re-implement your onChange function.此外,我们必须重新实现您的onChange function。 I suggest you review the docs on how to update states on functional component https://reactjs.org/docs/hooks-reference.html#usestate .我建议您查看有关如何更新功能组件https://reactjs.org/docs/hooks-reference.html#usestate状态的文档。


Anyway, you can change your code to this无论如何,您可以将代码更改为此

export default function App() {
  const [data, setData] = React.useState(DATA);

  // select the first option by default
  const [active, setActive] = React.useState(DATA[0].Id);

  function onChange(event) {
    setActive(event.target.value);
  }

  return (
    <Select value={active} onChange={onChange} fullWidth>
      <MenuItem disabled value="">
        <em>Please Select</em>
      </MenuItem>
      {data.map((item) => (
        <MenuItem key={item.Id} value={item.Id}>
          {item.Ad}
        </MenuItem>
      ))}
    </Select>
  );
}

...and I created a codesandbox for you to try it out. ...我创建了一个代码框供您试用。

编辑迷人的-dewdney-llw8r

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM