gpt4 book ai didi

javascript - React js 多选 [object Object], [object Object]

转载 作者:行者123 更新时间:2023-12-04 09:06:55 29 4
gpt4 key购买 nike

我正在使用 Material UI 进行多重选择。这是我的代码。

  <TextField
classes={{ root: classes.root }}
select
name="states"
id="states"
fullWidth
label="states where you want to work"
SelectProps={{
multiple: true,
value: states.states,
onChange: handleFieldChange
}}
>
{listStates.map(col => (
<MenuItem selected classes={{ selected: classes.selected }} key={col} value={col}>
<Checkbox checked={states.states.indexOf(col) > -1} />
<ListItemText primary={col} />
</MenuItem>
))}
</TextField>
这是 handleFieldChange 函数:
  const handleFieldChange = event => {
event.persist();
setStates(states => ({
...states,
[event.target.name]:
event.target.type === "checkbox"
? event.target.checked
: event.target.value
}));
};
这是状态数组:
const listStates = [ "Aguascalientes", "Baja California", "Baja California Sur", "Campeche", "CDMX", "Coahuila de Zaragoza", "Colima", "Chiapas", "Chihuahua", "Durango", "Guanajuato", "Guerrero", "Hidalgo", "Jalisco", "EDOMEX", "Michoacán de Ocampo", "Morelos", "Nayarit", "Nuevo León", "Oaxaca", "Puebla", "Querétaro", "Quintana Roo", "San Luis Potosí", "Sinaloa", "Sonora",  "Tabasco",  "Tamaulipas",  "Tlaxcala", "Veracruz de Ignacio de la Llave", "Yucatán", "Zacatecas"];
一切正常,值正确保存在 useState 中,但在屏幕上我没有看到我选择的值,我只看到 [object Object]、[object Object]。
你知道为什么会这样吗??
问候

最佳答案

问题似乎是缺少 Prop renderValue . value 是选择的值列表,但 renderValue 函数给出了实际的渲染逻辑。通过这个额外的 Prop ,它应该可以正常工作。
根据 official docs :
渲染值为 function(value: any) => ReactNode其中 value - 提供给组件的值。
示例代码:

SelectProps={{
multiple: true,
value: states.states,
onChange: handleFieldChange,
renderValue: (data) => <div>{data.join(", ")}</div>
}}
希望能帮助到你。回复任何疑问/澄清。

关于javascript - React js 多选 [object Object], [object Object],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63421357/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com