gpt4 book ai didi

javascript - 用户在删除按钮中传递选定的选项值 : React

转载 作者:可可西里 更新时间:2023-11-01 13:41:06 25 4
gpt4 key购买 nike

我有一个 react 选择表单,用户可以根据条件选择多个选项或单个选项。

我想让用户能够选择单个或多个选项,并将其从 JS 数组支持的选择中移除。

但是,当用户点击删除按钮时,我无法获取用户选择的选项

    //This is in my constructor
this.state = {
choices:["mango","apple","banana"]
};

//My remove choice function in React class
removeChoice(e){
let options = e.target.value;
console.log(options);

//code to remove selected options
}

//this is in my render function:
let choiceItems = this.state.choices.map((item,i) =>{
return (
<option key={item+i}>{item}</option>
)});

return(
......//code here
//this.props.multiSelect comes from a different component to allow/disallow user to select multiple options

<select name="choices" size="3" multiple={this.props.multiSelect?true:false}>
{choiceItems}
</select>
<button id="remove-choice"
onClick={this.removeChoice} value={choiceItems}>Remove Choice</button>
)

当我控制删除函数的选项时,我得到 [Object, Object...]。谁能建议一种替代方法来在删除按钮中传递在 {choiceItems} 中选择的值?

最佳答案

如果你想先选择选项,然后在点击按钮后删除它们,你也需要将选择的选项保存在状态中。所以整个组件将是这样的:

class App extends React.Component {
state = {
choices: ["mango", "apple", "banana"],
choicesForDelete: []
};
removeChoice = () => {
const choices = this.state.choices.filter(
choiceItem => !this.state.choicesForDelete.includes(choiceItem)
);
this.setState({ choices });
};
handleOptionClick = item => {
let { choicesForDelete } = this.state;
// checking if seleced choice exists in choicesForDelete
const exists = choicesForDelete.includes(item);
if (exists) {
choicesForDelete = choicesForDelete.filter(choice => choice !== item);
} else {
choicesForDelete = [...choicesForDelete, item];
}
this.setState({ choicesForDelete });
};
render() {
let choiceItems = this.state.choices.map((item, i) => {
return (
<option
className={
this.state.choicesForDelete.includes(item) ? "selected" : ""// check if choice is selected for styling purpose
}
key={item + i}
onClick={() => this.handleOptionClick(item)}
>
{item}
</option>
);
});
return (
<div>
<select name="choices" size="3" multiple={!!this.props.multiSelect}>
{choiceItems}
</select>
<button
id="remove-choice"
onClick={this.removeChoice}
value={choiceItems}
>
Remove Choice
</button>
</div>
);
}
}

您可以在 https://codesandbox.io/s/magical-haze-jtgvj 中找到工作示例

只是一个旁注:你可以这样写你的多重逻辑:

          multiple={!!this.props.multiSelect}

关于javascript - 用户在删除按钮中传递选定的选项值 : React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58476831/

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