[英]How to use "event.target.value" & "event.target.checked" together in reactjs?
I have few input fields few are type text and few are type checkboxes how can i get all the fields value together right now i'm able to only one at a time like given below example:-我的输入字段很少,很少是文本类型,很少是类型复选框,我现在如何将所有字段值放在一起,我一次只能输入一个,如下例所示:-
handleChange = event => {
this.setState({ [event.target.name]: event.target.value });
this.setState({ [event.target.name]: event.target.checked });
};
I'm not able to use both together.我不能同时使用两者。 Whats wrong with it?
它出什么问题了?
Thank you for your efforts!感谢你付出的努力!
You could use nullish coalescing operator :您可以使用无效合并运算符:
this.setState({ [event.target.name]: event.target.checked ?? event.target.value });
Or explicitly test for the property existence:或显式测试属性是否存在:
if('checked' in event.target) {
this.setState({ [event.target.name]: event.target.checked });
}
if('value' in event.target) {
this.setState({ [event.target.name]: event.target.value});
}
You could have a conditional statement depending on the input type property.根据输入类型属性,您可以有一个条件语句。 The
checked
property is only used with <input type=checkbox />
checked
的属性仅与<input type=checkbox />
一起使用
this.setState({ [event.target.name]:
event.target.type === 'checkbox'
? event.target.checked
: event.target.value
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.