在反应中使用 RadioGroup 时如何获取完整的事件对象

how to get the full event object when using RadioGroup in react

大家好,我遇到了一个小问题,我在 React 中使用 RadioGroup,我的问题是我无法获取事件对象,而我只获取了值,在我的例子中,我想获取名称和值onChange 事件发生

 <RadioGroup name="distance" onChange={handleChange}>
     <Radio value="0.5">0.5</Radio>
     <Radio value="2000">1</Radio>
     <Radio value="3000">2</Radio>
     <Radio value="4000">3</Radio>
     <Radio value="5000">4</Radio>
 </RadioGroup>

 const handleChange = (e) => {
    console.log(e);//getting only the value
   
  };

我没有尝试重现你的案例,但尝试这样的事情:

onChange={e => handleChange(e)}

比 cb

const handleChange = (e, value) => {console.log(e, value)}

此致!

chakra-ui

next version (v1.x)stable version v0.x有两个区别

<RadioGroup /> (v0.x)

onChange?: (
    event: React.ChangeEvent<HTMLInputElement>,
    value: IRadio["value"],
  ) => void;

并在 <RadioGroup /> (v1.x)

onChange?(nextValue: StringOrNumber): void;

如果您想参加活动,可以降级 chakra-ui

的版本

我 运行 遇到了同样的问题,因为我希望我的 handleChange 在任何类型的领域工作,我已经这样设置了。

const [formData, setFormData] = React.useState({
    inputField: "",
    checkBoxField: false,
    emailField: "",
    distance: "" /* radioField */
})


function handleChange(event) {
    const { name, value, type, checked } = event.target
    setFormData(prevFormData => {
        return {
            ...prevFormData,
            [name]: type === "checkbox" ? checked : value
        }
    })
}

作为变通方法,我编写了一个 returns 一个 事件的函数。

function createEvent(name, value) {
    return {
        target: {
            name: name,
            value: value,
            type: "radio",
            checked: false
        }
    }
}

然后我的 RadioGroup 会是这样的:

<RadioGroup
    name="distance"
    onChange={
        function(value) {
            props.handleChange(
                createEvent("distance", value)
            )
        }
    }
>
    <Radio value="0.5">0.5</Radio>
    <Radio value="2000">1</Radio>
    <Radio value="3000">2</Radio>
    <Radio value="4000">3</Radio>
    <Radio value="5000">4</Radio>
</RadioGroup>

但是,是的,将 name="distance" 作为 RadioGroup 的 属性 将不再重要。如果我们只需要 event.target 的几个属性,但仍然希望他们能尽快添加对完整事件对象的访问权限。