我有一个产品列表,我希望用户能够从列表中选择一个或多个。
如果我第一次单击/选择产品,console.log
则会显示正确的结果。但是,如果我单击两次或更多次,则会收到错误消息:
TypeError:无法读取 null 的属性“值”
我尝试了两种不同的策略,但都失败了(检查功能addSelectedProducts
):
第一个解决方案
function SearchProductForm() {
const [selectedProducts, setSelectedProducts] = React.useState([]);
function handleSubmit(event){
event.preventDefault();
}
function addSelectedProducts(event) {
console.log(event.target.value)
setSelectedProducts(oldArray => [...oldArray, event.target.value]);
console.log(selectedProducts)
}
return (
<div>
<Form>
<Form.Group controlId="exampleForm.ControlSelect2">
<Form.Label>Select the product(s) you are interested about:</Form.Label>
<Form.Control as="select" multiple onChange={(event) => addSelectedProducts(event)}>
<option value="product1">product1</option>
<option value="product2">product2</option>
<option value="product3">product3</option>
<option value="product4">product4</option>
<option value="product5">product5</option>
</Form.Control>
</Form.Group>
<Button variant="primary" type="submit" onClick={()=>handleSubmit()}>
Submit
</Button>
</Form>
</div>
);
}
export default SearchProductForm;
第二种解决方案
function SearchProductForm() {
const [selectedProducts, setSelectedProducts] = React.useState([]);
function handleSubmit(event){
event.preventDefault();
}
function addSelectedProducts(event) {
let options = event.target.options
for (var i = 0, l = options.length; i < l; i++) {
if (options[i].selected) {
setSelectedProducts(oldArray => [...oldArray, event.target.value]);
console.log(selectedProducts)
}
}
}
return (
<div>
<Form>
<Form.Group controlId="exampleForm.ControlSelect2">
<Form.Label>Select the product(s) you are interested about:</Form.Label>
<Form.Control as="select" onChange={(event) => addSelectedProducts(event)} multiple>
<option value="product1">product1</option>
<option value="product2">product2</option>
<option value="product3">product3</option>
<option value="product4">product4</option>
<option value="product5">product5</option>
</Form.Control>
</Form.Group>
<Button variant="primary" type="submit" onClick={()=>handleSubmit()}>
Search
</Button>
</Form>
</div>
);
}