我有一个名为“ 主要”的组件。
此“主要”组件包含一个名为“ 房屋”的组件。
此“房屋”组件包含一个名为“ ZoneButton ”的组件,其中包含一个 Button
如果我单击按钮,我想用“ ”中的另一个名为“ Saloon ”的组件替换“ 房屋”组件。 >主要”组件。
(卸载组件并装入(装入)另一个组件而不是第一个组件)
您知道我该怎么做吗? 在此先感谢:)
编辑是的,很抱歉,这是我的3个组成部分
Main.js
import React, { Component } from 'react';
import SearchBar from './SearchBar';
import House from './House';
// import Salon from './Saloon';
class Main extends Component {
render(){
return(
<div>
<House />
{/* <Saloon /> */}
</div>
)
}
}
export default Main;
House.js
import ZoneButton from './ZoneButton';
import zoneHouseData from './zoneHouseData';
class House extends Component {
render(){
const zoneComponents = zoneHouseData.map(item => <ZoneButton key={item.id} zoneName={item}/>)
return(
{zoneComponents}
)
}
}
ZoneButton.js
class ZoneButton extends Component {
render() {
return(
<React.Fragment>
<Button variant="contained" color="primary" onClick={this.unmountHouse} style={styles}>{this.props.zoneName.name}</Button>
</React.Fragment>
);
}
}
export default ZoneButton
并且zonHomeData.js包含按钮的数据
const zoneHouseData = [
{
id: 1,
symbol: '+',
name: 'Salon',
intro_text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc vel efficitur felis. Praesent at magna vestibulum lectus euismod interdum. Etiam mauris nulla, lacinia porttitor lacinia',
image: gray,
top: '34%',
left: '38%'
},
{
id: 2,
symbol: '+',
name: 'Cuisine',
intro_text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc vel efficitur felis. Praesent at magna vestibulum lectus euismod interdum. Etiam mauris nulla, lacinia porttitor lacinia',
image: gray,
top: '51%',
left: '38%'
},
{
id: 3,
symbol: '+',
name: 'Chambre',
intro_text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc vel efficitur felis. Praesent at magna vestibulum lectus euismod interdum. Etiam mauris nulla, lacinia porttitor lacinia',
image: gray,
top: '17%',
left: '46%'
},
]
export default zoneHouseData
答案 0 :(得分:1)
您可以在组件的状态中存储一个布尔值并切换子组件,或者调用它们并修改它们的类以隐藏或显示它们(如果需要css动画,这可能很有用)
Main.js
import React, { Component, Fragment } from 'react';
import SearchBar from './SearchBar';
import House from './House';
import Salon from './Saloon';
import ZoneButton from './ZoneButton';
class Main extends Component {
constructor(props) {
this.state = { zone: true }
}
toggleZone = () => {
this.setState(prevState => ({ zone: !prevState.zone }));
}
render(){
return(
<Fragment>
{ zone ? <House /> : <Saloon /> }
<ZoneButton toggleZone={this.toggleZone} />
</Fragment>
)
}
}
export default Main;
ZoneButton.js
import React, { Component, Fragment } from 'react';
class ZoneButton extends Component {
render(){
const { toggleZone } = this.props;
return(
<Fragment>
<Button variant="contained" color="primary" onClick={() => {toggleZone()}} style={styles}>{this.props.zoneName.name}</Button>
</Fragment>
)
}
}
export default ZoneButton;