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

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


 <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

   

  };


呼如林
浏览 132回答 3
3回答

人到中年有点甜

我没有尝试重现你的情况,但尝试这样的事情:onChange={e&nbsp;=>&nbsp;handleChange(e)}比CB中的const&nbsp;handleChange&nbsp;=&nbsp;(e,&nbsp;value)&nbsp;=>&nbsp;{console.log(e,&nbsp;value)}此致!

凤凰求蛊

next version (v1.x)和stable version v0.xof有两个区别chakra-ui<RadioGroup />在(v0.x)中onChange?: (&nbsp; &nbsp; event: React.ChangeEvent<HTMLInputElement>,&nbsp; &nbsp; value: IRadio["value"],&nbsp; ) => void;和<RadioGroup />(v1.x)onChange?(nextValue: StringOrNumber): void;如果您想参加该活动,您可以降级您的版本chakra-ui

慕田峪7331174

我遇到了同样的问题,因为我希望我handleChange在任何类型的领域工作,我已经这样设置了。const [formData, setFormData] = React.useState({&nbsp; &nbsp; inputField: "",&nbsp; &nbsp; checkBoxField: false,&nbsp; &nbsp; emailField: "",&nbsp; &nbsp; distance: "" /* radioField */})function handleChange(event) {&nbsp; &nbsp; const { name, value, type, checked } = event.target&nbsp; &nbsp; setFormData(prevFormData => {&nbsp; &nbsp; &nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ...prevFormData,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [name]: type === "checkbox" ? checked : value&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; })}作为解决方法,我编写了一个返回假事件的函数。function createEvent(name, value) {&nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; &nbsp; target: {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; name: name,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; value: value,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type: "radio",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; checked: false&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}然后我的RadioGroup会是这样的:<RadioGroup&nbsp; &nbsp; name="distance"&nbsp; &nbsp; onChange={&nbsp; &nbsp; &nbsp; &nbsp; function(value) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; props.handleChange(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; createEvent("distance", value)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }>&nbsp; &nbsp; <Radio value="0.5">0.5</Radio>&nbsp; &nbsp; <Radio value="2000">1</Radio>&nbsp; &nbsp; <Radio value="3000">2</Radio>&nbsp; &nbsp; <Radio value="4000">3</Radio>&nbsp; &nbsp; <Radio value="5000">4</Radio></RadioGroup>但是,是的,将name="distance"asRadioGroup的属性不再重要了。如果我们只需要 的一些属性event.target,但仍然希望它们能够尽快添加对完整事件对象的访问权限,则可以使用。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript