如何在React中为Select组件设置默认值,其中选项是MenuItem。

huangapple go评论56阅读模式
英文:

How to set a default value for a Select component from react with MenuItem as options

问题

以下是您提供的内容的翻译部分:

我一直在思考如何在使用MenuItem组件作为选项时,在React中设置Select的默认值。

首先,我使用以下的useEffect获取用户列表,该useEffect返回用户列表(包括id、firstName和lastName等属性):

const [userList, setUserList] = useState([]);
// 获取用户
useEffect(() => {
  userService
    .listUsersFromTeamRHandAdmin()
    .then((res) => {
      setUserList(res)
    });
}, [])

const {
  setFieldValue
} = useFormikContext();

const handleChange = (e) => {
  setFieldValue("user.id", setUserList[e.target.value].id)
}

我有以下的Select组件,我想将UserList的第一个用户的id作为默认值,并显示该用户的firstname和lastname。

<Select
  name="user"
  defaultValue={userList[0].id || ''}
  onChange={(e) => handleChange(e)}
  style={{
    width: "100%",
    marginBottom: "1em"
  }}
>
  {
    Object.keys(userList).map((e, keyIndex) => {
      return (
        <MenuItem key={keyIndex} value={e}>
          {userList[e].firstName} {userList[e].lastName}
        </MenuItem>
      );
    })
  }
</Select>

有谁知道我如何做到这一点?

编辑:

例如,UserList数组可能包含如下内容:

0: Object { id: 1, firstName: "Britta", lastName: "Perry",  }
1: Object { id: 2, firstName: "Troy", lastName: "Barnes",  }
英文:

I've been wondering how to set the default value of a Select in React when we use the MenuItem component as options.

First, I get an user list with the following useEffect that returns a list of users (objects with id, firstName and lastName among other attributes)

  const [userList, setUserList] = useState([]);
  //Get users
  useEffect(() =&gt; {
    userService
    .listUsersFromTeamRHandAdmin()
      .then((res) =&gt; {
        setUserList(res)
    });
  }, [])
  
  const {
    setFieldValue
  } = useFormikContext();

  const handleChange = (e) =&gt; {
    setFieldValue(&quot;user.id&quot;, setUserList[e.target.value].id)
  }

I have the following Select component, where I would like to have the first user's id of the UserList as a default value, with this user's firstname and lastname displayed.

&lt;Select
    name=&quot;user&quot;
    defaultValue={userList[0].id || &#39;&#39;}
    onChange={(e) =&gt; handleChange(e)}
    style={{
        width: &quot;100%&quot;,
        marginBottom: &quot;1em&quot;
    }}
&gt;
    {
        Object.keys(userList).map((e, keyIndex) =&gt; {
            return (
                &lt;MenuItem key={keyIndex} value={e}&gt;
                    {userList[e].firstName} {userList[e].lastName}
                &lt;/MenuItem&gt;
            );
        })
    }
&lt;/Select&gt;

Does anyone know how I can do that ?

Edit:

For example, the array of UserList would contain something like:

0: Object { id: 1, firstName: &quot;Britta&quot;, lastName: &quot;Perry&quot;, … }
​
1: Object { id: 2, firstName: &quot;Troy&quot;, lastName: &quot;Barnes&quot;, … }

答案1

得分: 1

To have a defaultValue in the MaterialUi Select Component, you should provide a defaultValue that exists in your choices. Please try this:

import "./styles.css";
import { Select, MenuItem } from "@mui/material";

export default function App() {
  const arr = [
    { id: 1, firstName: "Britta", lastName: "Perry" },
    { id: 2, firstName: "Troy", lastName: "Barnes" }
  ];

  return (
    <div className="App">
      <Select
        name="user"
        defaultValue={arr[0].firstName + arr[0].lastName || ""}
        onChange={(e) => handleChange(e)}
        style={{
          width: "100%",
          marginBottom: "1em"
        }}
      >
        {arr.map((el) => (
          <MenuItem key={el.id} value={el.firstName + el.lastName}>
            {el.firstName + el.lastName}
          </MenuItem>
        ))}
      </Select>
    </div>
  );
}

You can add a separator between firstName and lastName but keep the same syntax in defaultValue too.

英文:

To have a defaultValue in the MaterialUi Select Component you should provide a defaultValue that exist in your choices, please try this :

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

import &quot;./styles.css&quot;;
import { Select, MenuItem } from &quot;@mui/material&quot;;
export default function App() {
  const arr = [
    { id: 1, firstName: &quot;Britta&quot;, lastName: &quot;Perry&quot; },
    { id: 2, firstName: &quot;Troy&quot;, lastName: &quot;Barnes&quot; }
  ];
  return (
    &lt;div className=&quot;App&quot;&gt;
      &lt;Select
        name=&quot;user&quot;
        defaultValue={arr[0].firstName + arr[0].lastName || &quot;&quot;}
        onChange={(e) =&gt; handleChange(e)}
        style={{
          width: &quot;100%&quot;,
          marginBottom: &quot;1em&quot;
        }}
      &gt;
        {arr.map((el) =&gt; (
          &lt;MenuItem key={el.id} value={el.firstName + el.lastName}&gt;
            {el.firstName + el.lastName}
          &lt;/MenuItem&gt;
        ))}
      &lt;/Select&gt;
    &lt;/div&gt;
  );
}

<!-- end snippet -->

As you can see, the defaultValue and the menuItem have the same syntaxe, this a working demo that I've created for this

you can add separator between firstName and lastName but keep the same syntaxe in defaultValue too.

huangapple
  • 本文由 发表于 2023年4月13日 15:47:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76002895.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定