簡體   English   中英

React Hooks Onchange 同步

[英]React Hooks Onchange Synchronize

我將我的應用程序從類模型傳遞給鈎子,在我的代碼中,我有一個下拉列表,當執行 onChange 方法時,它會執行以下操作:

filter(event)
{
    this.setState({
        selectedFilter: event.target.value
      },() => { this.chargeInfo(); });
}

在我的類模型中工作完美,但我不知道如何使用鈎子來做到這一點,我通過道具傳遞了方法 chargeInfo() 和變量 selectedFilter 因為這個組件是一個孩子,所以我有的是這個代碼:

<Dropdown onChange={onChangeDropdown} />

const onChangeDropdown = function(event)
{
    props.changeSelectedFilter(event.target.value);//this do setSelecedFilter in the parent
    props.chargeInfo();//this is the method of the parent that do something
}

我怎樣才能在同步模式下適應這個,首先執行 props.changeSelectedFilter 然后執行 props.chargeInfo?。

您可能需要像這樣使用 State Hook:

// setting up the default dropdown value
const [dropdownValue, setDropdownValue] = useState('Some Value');

// later, setting a new dropdown value
setDropdownValue('New Value')

有關更多信息,請參閱https://reactjs.org/docs/hooks-state.html

我使用useEffect解決了:

useEffect(
    () => {
    // eslint-disable-next-line react-hooks/exhaustive-deps
    props.chargeInfo();}, [props.selectedFilter]
    )

const onChangeDropdown = function(event)
{
    props.changeSelectedFilter(event.target.value);
}

return(

    <Dropdown style={{ marginRight: 10, }} value={props.selectedFilter} options={filters} 
    onChange={onChangeDropdown} optionLabel="name" placeholder="Filter by" />
)

暫無
暫無

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

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