![](/img/trans.png)
[英]React Native Element Dropdown, Passing Dropdown selected value to parent component
[英]Passing selected value of Dropdown into API in react
嗨,当页面加载时,我需要在dropdown
列表中填充列表,因此我将其放入componentDidMount()
中。
componentDidMount() {
axios.get(`http://localhost:8080/country_code`).then((res) => {
const countryData = res.data;
this.setState({ countryData });
});
}
此数据需要是下拉列表的一部分。
<select id="dropdown">
{this.state.countryData.map((countryData) => (
<option key={countryData} value={countryData}>
{countryData}
</option>
))}
</select>
列表显示如下。
我的要求是,如果用户 select dropdown list
中的任何value
都应在API
中作为参数传递给backend
。
我需要在Select
或Option
中进行哪些更改。 我知道如何使用axios
在reactjs
中编写调用 API 。我会管理的。 我的更新代码如下。
<select id="dropdown" onChange={this.downLoadFile(e)}>
{this.state.countryData.map((countryData) => (
<option key={countryData} value={countryData}>
{countryData}
</option>
))}
</select>
downLoadFile(e) {
this.setState({ selectValue: e.target.value });
alert(selectValue);
}
this.state = {
countryData: [],
selectValue: '',
};
this.handleChange = this.handleChange.bind(this);
this.downLoadFile = this.downLoadFile.bind(this);
}
它不工作。 我做错了什么?
您应该将 function 传递给 onChange 事件。 喜欢:
<select id="dropdown" onChange={(e) => {this.downLoadFile(e)}}>
或者
<select id="dropdown" onChange={this.downLoadFile}>
你这样做的方式只是传递 this.downLoadFile 的返回值
您应该在更新选定的 state 后获取 API。
downLoadFile(e) {
this.setState({ selectValue: e.target.value }, () => {
fetchSomeApi(this.state.selectValue).then((res) => {
updateSomewhere(res);
}).catch((error) => console.error(error));
});
alert(selectValue);
}
this.setState
有第二个参数作为回调。 所以你可以在 state 更新事件之后使用它。
此外,您可以更新 function 调用。
onChange={this.downloadFile)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.