import React from "react"; import { render } from "react-dom"; class App extends React.Component { constructor(props) { super(props); this.state = { projects: [], value: "" }; } componentDidMount() { // 模拟ajax调用,成功之后把需要改变的默认值赋值给this.state.value setTimeout(() => { this.setState({ projects: [ { id: 1, name: "花生" }, { id: 2, name: "苹果" }, { id: 3, name: "杨桃" } ], value: 1 }); }, 3000); } handleClick() { this.setState({ projects: [ { id: 4, name: "水果" }, { id: 5, name: "西瓜" }, { id: 6, name: "哈哈哈" } ], value: 4 }); } handleChange = e => { this.setState({ value: e.target.value }); }; render() { let projects = this.state.projects; return ( <div> <button onClick={this.handleClick.bind(this)}>异步拉取数据</button> {/* 这里不用再去判断project的长度是否大于0,在ajax里面做判断就行,如果小于零或者不存在它就是默认值 */} <select defaultValue="" value={this.state.value} onChange={this.handleChange} > {projects.length > 0 && projects.map((item, i) => { return ( <option key={i} value={item.id}> {item.name} </option> ); })} </select> </div> ); } } render(<App />, document.getElementById("root"));
react写一个select组件的实现代码(2)
内容版权声明:除非注明,否则皆为本站原创文章。
转载注明出处:http://www.heiqu.com/6b4bcbc67f5060f385b7ad408a26ded3.html