javascript - 如何在 ReactJS 中处理多选表单
问题描述
我尝试在 ReactJS中处理多表单选择选项。我试图启发 javascript 经典代码来处理这个问题,但我失败了。
我的代码只是不向我发送选择的值。怎么处理?
这是我的代码:
class ChooseYourCharacter extends React.Component {
constructor(props) {
super(props);
this.state = {value: 'coconut'};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.option});
}
handleSubmit(event) {
alert('Your favorite flavor is: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Pick your favorite La Croix flavor:
<select multiple={true} value={this.state.value} onChange={this.handleChange}>
<option value="grapefruit">Grapefruit</option>
<option value="lime">Lime</option>
<option value="coconut">Coconut</option>
<option value="mango">Mango</option>
</select>
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
ReactDOM.render(
<ChooseYourCharacter/>,
document.getElementById('root')
)
解决方案
根据我的基本理解,当您尝试在 reactJS 中处理Select 表单元素时,您会在 HTMLOptionsCollection 中生成一个对象。
此对象方法和属性的基本根是e.target.options。
您的项目存储在 e.target.options.value 属性中。
要访问存储在 options.value 对象中的值,您可以使用 [i] 循环值,因此可以使用 e.target.options[i].value 属性。
e.target.options[i].value 返回字符串数据类型。
按照我刚才所说的,我假设对象的存储遵循一个数字增加约定,如下所示:
e.target.options[i].value where { [i] : value, [i +1] : value (...)}...
通过使用 e.target.options[i].selected 您可以控制是否有值存储在特定位置。
e.target.options[i].selected 返回一个布尔值,用于处理代码流。
现在由你决定。
这是我在 JSX 中使用 javascript 代码处理多选表单的代码:
// Create the React Component
class ChooseYourCharacter extends React.Component {
// Set the constructor
constructor(props) {
super(props);
this.state = {value: 'coconut'};
// bind the functions
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
// extract the value to fluently setState the DOM
handleChange (e) {
var options = e.target.options;
var value = [];
for (var i = 0, l = options.length; i < l; i++) {
if (options[i].selected) {
value.push(options[i].value);
}
}
this.setState({value: value});
}
// display in client-side the values choosen
handleSubmit() {
alert("you have choose :" + this.state.value);
}
(...)
推荐阅读
- java - 如何在 contenteditable 处于活动状态时在 Vaadin Flow 中获取 div 的内部 html
- javascript - Mongoose 无法从 MongoDB 数据库中获取数据
- c# - 通过 WPF 转换器更改字体颜色
- c++ - 如何在 openssl 中从 SHA 切换到 SHA-1
- sql - 如何通过查看一列将数据导出到不同的文件?
- javascript - 在 Laravel 中使用 JavaScript 动态填充某些数据时出现未定义变量的错误
- node.js - 从多个集合创建视图 MongoDB
- javascript - 无法获取 /test - expressjs
- angular - 无法在 SafeSubscriber._next 读取未定义的属性“推送”
- apache-spark - PySpark 中 XGBoost 的跟踪器问题