簡體   English   中英

從引導表單中進行多選 - React Hooks

[英]Multi-select from bootstrap form - React Hooks

我有一個產品列表,我希望用戶能夠從列表中選擇一個或多個。

如果我第一次單擊/選擇產品, console.log會顯示正確的結果。 但是,如果我單擊兩次或更多次,則會收到錯誤消息:

類型錯誤:無法讀取 null 的屬性“值”

我嘗試了兩種不同的策略,但都失敗了(檢查 function 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>
    );
}

Ricardo 在他們的回答中談到了事件池,但我想提出一個不需要持久化事件的解決方案,這對我來說有點代碼味。

您可以一次獲取所有選定的選項,然后設置它們,而不是嘗試將新的 state 與舊的 state 合並。

function addSelectedProducts(event) {
  // Alternative if you need to target ie
  // const selectedOptions = [...event.target.options].filter(o => o.selected).map(o => o.value)

  const selectedOptions = [...event.target.selectedOptions].map(o => o.value)

  setSelectedProducts(selectedOptions)
}

您遇到上述錯誤的原因是

setSelectedProducts(oldArray => [...oldArray, event.target.value]);

是異步的,並且在調用回調時,您的事件不再存在。 在此處查看更多信息: https://reactjs.org/docs/events.html#event-pooling

https://codesandbox.io/s/zealous-haibt-hp6mp

嗨,您檢查過文檔嗎? 也許您必須添加event.persist()因為您正在處理function內的event

 function addSelectedProducts(event) {
        event.persist()
        console.log(event.target.value)
        setSelectedProducts(oldArray => [...oldArray, event.target.value]);
        console.log(selectedProducts)
    }

其他解決方案可能涉及為event.target.value設置一個變量:

 function addSelectedProducts(event) {
        let value = event.target.value;
        console.log(event.target.value)
        setSelectedProducts(oldArray => [...oldArray, event.target.value]);
        console.log(selectedProducts)
    }

我認為您可以嘗試onChange={addSelectedProducts}而不是onChange={(event) => addSelectedProducts(event)}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM