2 回答
TA贡献1816条经验 获得超6个赞
import React, { Component } from "react";
class Dropdown extends Component {
constructor(props) {
super(props);
this.state = {
Genres: [],
Books: [],
selectedGenre: '--Choose Genre--',
selectedBook: '--Choose Book--'
};
this.ChangeGenre = this.ChangeGenre.bind(this);
this.ChangeBook = this.ChangeBook.bind(this);
}
componentDidMount() {
this.setState({
Genres: [
{ name: "Fiction", Books: ["GOT", "LOTR", "Harry Potter"] },
{ name: "Murder", Books: ["Dragon", "Tattoo", "Girl"] },
{ name: "Thriller", Books: ["Angel", "Lost Symbol", "Davinci"] }
]
});
}
ChangeGenre(e) {
e.preventDefault();
const Books = this.state.Genres.find(
(genre) => genre.name === e.target.value
).Books;
this.setState({ selectedGenre: e.target.value, Books });
}
ChangeBook(e) {
e.preventDefault();
this.setState({ selectedBook: e.target.value });
}
render() {
return (
<div id="container">
<h2>Cascading or Dependent Dropdown using React</h2>
<div>
<label>Genre</label>
<select
placeholder="Genre"
value={this.state.selectedGenre}
onChange={this.ChangeGenre}
>
<option>--Choose Genre--</option>
{this.state.Genres.map((genre, key) => {
return <option key={key}>{genre.name}</option>;
})}
</select>
</div>
<div>
<label>Books</label>
<select
placeholder="Books"
value={this.state.selectedBook}
onChange={this.ChangeBook}
disabled={this.state.selectedGenre === '--Choose Genre--'}
>
<option>--Choose Book--</option>
{this.state.Books.map((book, key) => {
return <option key={key}>{book}</option>;
})}
</select>
</div>
</div>
);
}
}
export default Dropdown;
添加回答
举报