A在React JS中有一个数组对象,我想循环遍历它。
我的代码如下:
let data = [
{make: "Volkswagen", models: ["Golf", "Passat", "Polo", "Tiguan"]},
{make: "Skoda", models: ["Fabia", "Octavia", "Superb"]},
{make: "Audi", models: ["A1", "A3", "A5", "Q3", "Q5"]}
];
export default class makeModel extends React.Component {
constructor(props) {
super(props);
this.state = {
show: false,
make: null
}
}
handleMake(event){
event.preventDefault();
this.setState({make: event.target.name, show: !this.state.show});
}
render() {
const language = this.props.language;
let style = {display: "none"};
if(this.state.show) style = {display: "block"};
return (
<div>
<div className="priceTitle">{language.makeAndModel}</div>
{data.map( (car, i) => {
return (
<div key={i} className="makeModel">
<Link to="/" className="make" name={car.make} onClick={this.handleMake.bind(this)}>{car.make}</Link>
<div className="models" style={style}>
{car.models.map((m, i) => {
if(car.models.indexOf(m) > -1 && car.make === this.state.make){
return <div key={i}>{m}</div>
}
})}
</div>
</div>
)
})}
</div>
);
}
}
我想显示所有品牌的清单。然后点击我想要显示的所有模型。
我的代码有效。但是onClick上显示了所有三个带有类模型的div。但只有在点击的模型中才会显示模型。如何使用类模型隐藏所有div并仅显示所单击的div?
通常,有没有更好的方法呢?
答案 0 :(得分:2)
试试这个:
import React from 'react';
let data = [
{make: "Volkswagen", models: ["Golf", "Passat", "Polo", "Tiguan"]},
{make: "Skoda", models: ["Fabia", "Octavia", "Superb"]},
{make: "Audi", models: ["A1", "A3", "A5", "Q3", "Q5"]}
];
const ModelLink = ({models,make,handleMake,isDisplay}) => {
const modelList = isDisplay ? models.map((m, i) => <div key={i}>{m}</div>) : "";
return (
<div className="makeModel">
<h3 to="/" className="make" name={make} onClick={handleMake}>{make}</h3>
<div className="models" >
{modelList}
</div>
</div>
)
}
export default class makeModel extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedMake: null
}
}
handleMake(event,name){
event.preventDefault();
const nextMake = this.state.selectedMake !== name ? name : null;
this.setState({selectedMake: nextMake});
}
render() {
const {selectedMake} = this.state;
return (
<div>
{data.map((car, i) => {
return (
<ModelLink key={i}
models={car.models}
make={car.make}
isDisplay={car.make === selectedMake}
handleMake={(e) => this.handleMake(e,car.make)}
/>
)
})}
</div>
);
}
}