如何恢复另一个组件的价值?



我想从子组件(DropDown(中获取值并将它们显示在父类(App(中,

我解释说,我有一个导入到 App 类中的下拉列表,当我在此下拉列表中选择一个值时,我会修改我的类 App 中显示的数据,

类应用程序 :

class App extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
station: [],
stationValue: ''
}
}
getParking = async () => {
try {
const reponse = await axios.get(URL + "station/");
this.setState({
station: reponse.data['hydra:member']
});
} catch (e) {
console.log(e)
}
};
getData = async () => {
try {
const response = await axios.get(URL + "events?station=station_id");
this.setState({
data: response.data["hydra:member"]
});
} catch (error) {
console.log(error)
}
};
componentDidMount() {
this.getData();
this.getParking()
setInterval(this.appendData, 1000)
}
render() {
const {data, station} = this.state;
return (
<div>
<header>
<Dropdown dataStation={station}/>
</header>
{
data.map((item, key) =>
<div key={key}>
<>
{item.label}
</>
</div>
)
}
</div>
)
}
}

组合下拉:

const Dropdown = ({dataStation}) => {
const [showMenu, setShowMenu] = useState(false);
const [selectItem, setSelectItem] = useState(showMenu);
const showList = () => {
setShowMenu(!showMenu)
};
const toggleSelected = (list) => {
setSelectItem(list.name);
setShowMenu(false)
};
return (
<>
<div className="dropdown-list-style" onClick={showList}>
<div style={{display: 'inline'}}>
{showMenu
? (<div style={{textAlign: 'right'}}><ChevronUp/></div>)
: (<div style={{textAlign: 'right'}}><ChevronDown/></div>)
}
{selectItem}
</div>
</div>
<div className="dropdown-list-style" style={{display: showMenu ? 'block' : 'none'}}>
{
dataStation.map((list, index) =>
<div key={index} onClick={() => toggleSelected(list)}>
{list.name}
</div>
)
}
</div>
</>
)};
因此,当我在下拉列表中选择例如值"A">

时,我将不得不显示"A"中的元素,例如"A"有一个 Id "1",这个 id 我将不得不恢复它并将其放入我的函数 (getData( 中,该函数位于 A 类中。 当我输入手动编写的值时,我的代码有效,例如当我直接用 1 代替 (station_id(,但当我希望通过下拉列表检索 id 时不会。

你能帮我吗?

在应用程序组件中进行设置工作站值的回调

setStation=(stationValue)=>{
this.setState({stationValue:stationValue})
}

像这样传递到下拉列表

<Dropdown dataStation={station} setStation={this.setStation}/>

内部多普多组合 在单击以下项目时使用它:

{
dataStation.map((list, index) =>
<div key={index} onClick={() =>{toggleSelected(list); props.setStation(list)}}>
{list.name}
</div>
)
}

编辑

您可以在getData url中使用站值,例如

getData = async () => {
try {
const response = await axios.get(URL + "events?station="+this.state.stationValue);
this.setState({
data: response.data["hydra:member"]
});
} catch (error) {
console.log(error)
}
};

最新更新