gpt4 book ai didi

javascript - 如何在 ReactJS 中处理多个选择表单

转载 作者:搜寻专家 更新时间:2023-11-01 05:27:49 24 4
gpt4 key购买 nike

我尝试在 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 中处理选择表单元素时,您会在 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 返回一个 bool 值,用于处理代码流。

现在就看你的了。


这里是我用 javascript 代码在 JSX 中处理多个选择表单的代码:

// 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);

}


(...)

关于javascript - 如何在 ReactJS 中处理多个选择表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50090335/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com