我有这段代码调用 Web 服务并将来自该 WS 的名称显示到 Material UI 的 Dropdown 组件中,
我想要做的是使用来自 WS 的第一个元素设置下拉列表的默认值,并且还能够选择下拉列表中的任何选项,我阅读了一些关于“状态”的内容,但没有得到它真的很好在代码级别。
我是 React 的新手并且自己学习,但一些帮助会很好。
import React, { Component } from 'react';
import DropDownMenu from 'material-ui/DropDownMenu';
import MenuItem from 'material-ui/MenuItem';
export default class WebserviceTest extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
};
this.renderOptions = this.renderOptions.bind(this);
}
componentDidMount() {
const url = 'https://randomuser.me/api/?results=4';
fetch(url)
.then(Response => Response.json())
.then(findResponse => {
console.log(findResponse);
this.setState({
data: findResponse.results
});
});
}
//will set wahtever item the user selects in the dropdown
handleChange(event, index, value) {this.setState({ value });}
//we are creating the options to be displayed
renderOptions() {
return this.state.data.map((dt, i) => {
return (
<div key={i}>
<MenuItem
label="Select a description"
value={dt.name.first}
primaryText={dt.name.first} />
</div>
);
});
}
render() {
return (
<div>
<DropDownMenu value={this.state.name} onChange={this.handleChange}>
{this.renderOptions()}
</DropDownMenu>
</div>
);
}
}
提前致谢。
问候。