慕勒3428872
2022-12-22 15:40:44
我有一個(gè)組件,它在下拉列表中顯示數(shù)據(jù)列表,并且有一個(gè)選項(xiàng)可以搜索這些用作過(guò)濾器的數(shù)據(jù)。這是我的代碼:import React, { useState } from 'react';import PropTypes from 'prop-types';import classNames from 'classnames';import Popover from '../../Popover';import Input from '../../Input';import Icon from '../../Icon';import IconButton from '../../IconButton';const DropDownFilter = props => { const { label, options, onChange, isSearchEnabled } = props; const [activeOption, setActiveOption] = useState({}); const [filter, setfilter] = useState(''); const searchFilter = event => { setfilter(event.target.value); }; const removeFilter = () => { setfilter(''); }; const lowercasedFilter = filter.toLowerCase(); const filteredData = options.filter(item => { return Object.keys(item).some( key => typeof item[key] === 'string' && item[key].toLowerCase().includes(lowercasedFilter) ); }); const labelText = activeOption.label ? activeOption.label : label; const handleSelectedOption = option => { setActiveOption(option); onChange(option); }; return ( <div className="filter"> <Popover linkText={labelText} size="small" direction="bottom-left"> {isSearchEnabled && ( <div className="filter__search"> <Input value={filter} onChange={searchFilter} preIcon={ <div role="presentation"> <Icon name="search" /> </div> } 這是它的 gif:https ://recordit.co/HtalUtuPsj現(xiàn)在在搜索期間我想將搜索參數(shù)的值發(fā)送到另一個(gè)組件,該值將用于從數(shù)據(jù)庫(kù)或正在該新組件中處理的任何其他外部數(shù)據(jù)源進(jìn)行搜索。例如,如果我正在搜索Ratings,這個(gè)組件應(yīng)該在它自己的組件中的現(xiàn)有選項(xiàng)列表中搜索它,同時(shí)它會(huì)Ratings在任何其他外部數(shù)據(jù)源或數(shù)據(jù)庫(kù)中搜索。此外部網(wǎng)絡(luò)調(diào)用、搜索或任何其他功能將在其他組件中處理。所以這個(gè)組件只會(huì)發(fā)送搜索參數(shù);例如Ratings實(shí)時(shí)到其他組件。我可以想到一個(gè)想法,比如讓 searchParam 處于某個(gè)狀態(tài)并將 setState 值傳遞給一個(gè)新的道具,該道具將通過(guò) onSearchParamChange 函數(shù)調(diào)用,這個(gè)新函數(shù)將通過(guò)回調(diào)傳遞數(shù)據(jù),另一個(gè)組件將獲得通過(guò)調(diào)用該組件的 props 來(lái)獲取數(shù)據(jù)。我不確定這是否是正確的方法,而且我也無(wú)法在代碼中實(shí)現(xiàn)這個(gè)想法。有沒(méi)有更好的方法呢?如果是這樣,那編碼實(shí)現(xiàn)是什么?
1 回答

慕村9548890
TA貢獻(xiàn)1884條經(jīng)驗(yàn) 獲得超4個(gè)贊
如果您需要傳遞給父組件,您應(yīng)該能夠使用onChange傳遞給您的組件的道具,就像您在handleSelectedOption函數(shù)中所做的那樣。該函數(shù)實(shí)際上是將選擇的選項(xiàng)傳遞給父組件。如果你想在用戶輸入時(shí)傳遞給父組件,那么你也應(yīng)該調(diào)用該onChange函數(shù)searchFilter:
const searchFilter = event => {
const option = event.target.value);
setfilter(option);
onChange(option);
};
如果你想將它傳遞給子組件,你可以將它作為 prop 傳遞:
<ChildComponent filter={ filter } />
添加回答
舉報(bào)
0/150
提交
取消