有三个女主角,但我计划增加她们的数量,但为此,代码需要变得可扩展,现在不是。 在每个女主角内部都有一个调用另一个地图组件的按钮,只有一个地图必须同时打开。
这是代码,但是怎么做才能让你轻松增加div的数量?
import React, { Component } from 'react';
import Maps from '../components/map'
import data from '../assets/data'
import './App.scss'
export default class App extends Component {
constructor(props) {
super(props);
this.state = { showMap1: false, showMap1Value: "Open map", showMap2: false, showMap2Value: "Open map", showMap3: false, showMap3Value: "Open map" }
this.onClick1 = this.onClick1.bind(this)
this.onClick2 = this.onClick2.bind(this)
this.onClick3 = this.onClick3.bind(this)
this.onClick = this.onClick.bind(this)
}
onClick1() {
if (this.state.showMap1 == true) {
this.setState({showMap1: false, showMap1Value:"Open map"})
}
if (this.state.showMap1 ==false) {
this.setState({showMap1: true, showMap2: false, showMap3: false, showMap1Value:"Close map"})
}
}
onClick2() {
if (this.state.showMap2 == true) {
this.setState({showMap2: false, showMap2Value:"Open map"})
}
if ( this.state.showMap2 ==false) {
this.setState({showMap2: true, showMap1: false, showMap3: false, showMap2Value:"Close map"})
}
}
onClick3() {
if (this.state.showMap3 == true) {
this.setState({showMap3: false, showMap3Value:"Open map"})
}
if (this.state.showMap3 ==false) {
this.setState({showMap3: true, showMap1: false, showMap2: false, showMap3Value:"Close map"})
}
}
onClick() {
}
render() {
return (
<div className="App">
<div>
<h1>{data[0][0]}</h1>
<p>
{data[0][1]}
</p>
<input type="button" value={this.state.showMap1Value} onClick={this.onClick1} />
<div>
{ this.state.showMap1 ? <Maps item="0"/> : null }
</div>
</div>
<div>
<h1>{data[1][0]}</h1>
<p>
{data[1][1]}
</p>
<input type="button" value={this.state.showMap2Value} onClick={this.onClick2} />
<div>
{ this.state.showMap2 ? <Maps item="1"/> : null }
</div>
</div>
<div>
<h1>{data[2][0]}</h1>
<p>
{data[2][1]}
</p>
<input type="button" value={this.state.showMap3Value} onClick={this.onClick3} />
<div>
{ this.state.showMap3 ? <Maps item="2" /> : null }
</div>
</div>
</div>
);
}
}
答案 0 :(得分:1)
诀窍是将地图存储在状态中的数组中,然后使用索引跟踪您正在使用的地图。
class App extends Component {
constructor() {
super();
this.state = {
maps: [
{ showing: false, value: "Open map" },
{ showing: false, value: "Open map" },
{ showing: false, value: "Open map" }
]
};
}
onClick(index) {
if (this.state.maps[index].showing) {
// Open the map at this index
} else {
// Close the map at this index
}
}
render() {
return (
<div className="app">
{this.state.maps.map((map, index) => (
<div>
<h1>{data[index][0]}</h1>
<p>{data[index][1]}</p>
<input type="button" value={map.value} onClick={e => this.onClick(index)} />
<div>{map.showing && <Maps item={index} />}</div>
</div>
})}
</div>
)
}
}