1

在我的选择框中处理 onChange 事件时,我需要能够发送两个值,但是我不确定这样做的方法,因为它们当前是作为字符串发送的。我正在使用 react-bootstrap 进行反应。

 const DropDown = () => {
     
    const handleOnchange = (event) => { 

      console.log(event.target.value)
      
        const filter = event.target.value[0];
        const initialState = [...initialValues]
        let result = [];

      console.log(event)

        setDefaultSelect(event.target.name)

        if(event.target.value === 'Show All') {
            setValues(initialState);
        }
        else {  
            initialState.forEach(item => {
                let found = item.store_category.filter(item => item == filter);
                if (found.length) {
                    result.push(item);
                }
            });
            setValues(result);
        }
    }

    return (
      <Form>
        <Form.Group controlId="exampleForm.SelectCustom">
          <Form.Control onChange={(e) => handleOnchange(e)} as="select" custom>
          <option className="pl-2" hidden>{defaultSelect}</option>
            <option>Show All</option>
            {storeCategorys.map((item, index) => (
              <option value={{itemId: item.id, itemName: item.name}} key={index}>{item.name}</option>
            ))}
          </Form.Control>
        </Form.Group>
      </Form>
    );
  }
4

1 回答 1

1

如何使用useEffect而不是handleOnchange

const DropDown = () => {
    const [selectedItem, setSelectedItem] = useState({});
    
    useEffect(() => {
      console.log(selectedItem);
    }, [selectedItem]);  // will be fired when `selectedItem` is changes

    ...

            {storeCategorys.map((item, index) => (
              <option
                value={{itemId: item.id, itemName: item.name}} 
                key={index}
                onClick={() => {setSelectedItem(item)}}  // will fire `useEffect`
                                                         // on `selectedItem`
              >{item.name}</option>
            ))}

    ...

}
于 2021-02-03T16:42:33.060 回答