MUI Radio 在选中时在 onChange 中传递标签和值

MUI Radio pass the label and value in onChange when selected

我正在使用 reactjs,我有一个 MUI RadioGroup 组件,我想从中将标签与所选值一起传递。

我的单选按钮代码

<RadioGroup
    aria-label="am-time-in"
    value={state.AM_time_in_value}
    name="radio-buttons-group"
    onChange={onChangeRadioAMIN}
>
    {
        state.AM_timelogs_IN ?
            state.AM_timelogs_IN.map((radio) => (
                <Tooltip
                    title={
                        <>
                            <Typography variant="caption">
                                {`Scan Location: ${radio.scan_location}`}
                            </Typography>
                            <br />
                            <Typography variant="caption">
                                {`Scanned By: ${radio.scanned_by}`}
                            </Typography>
                        </>
                    }
                >
                    <FormControlLabel value={radio.time_check.split(',')[1].slice(1)} control={<Radio size="small" />} label={radio.time_standard} item={radio} />
                </Tooltip>
            )) : null
    }
</RadioGroup>

我的onchange函数:

const onChangeRadioAMIN = (event, value) => {   
        console.log(event);     
        event.persist();        
        setState((prev) => ({
            ...prev,
            AM_time_in_value: value,
        }));
}

您需要创建一个 id 字段来识别您的选项:

const options = [
  {
    id: 0,
    scan_location: value_1,
    scanned_by: value_2,
    time_check: value_3,
    time_standard: value_4,
  },
  {
    id: 1,
    scan_location: value_1,
    scanned_by: value_2,
    time_check: value_3,
    time_standard: value_4,
  },
  ...
];

并将 id 传递给 FormControlLabelvalue 属性,当用户更改选项时,change 处理程序将收到 id。请注意,您不能将选项对象传递给 value,因为它将被转换为字符串,因此您只能得到 [object Object] 否则:

{options.map((o) => (
  <FormControlLabel
    value={o.id} // <---- pass a primitive id value, don't pass the whole object here
    control={<Radio />}
    label={o.time_standard}
  />
))}

然后您可以从 id 中找到包含您需要的所有字段的选定选项对象:

<RadioGroup
  onChange={(e, value) => {
    const id = parseInt(value, 10);
    const option = options.find((o) => o.id === id);
    // setState
  }}