gpt4 book ai didi

javascript - React - 单击不是其子组件的组件时呈现组件

转载 作者:行者123 更新时间:2023-11-29 15:21:09 24 4
gpt4 key购买 nike

我正在尝试弄清楚如何让组件在 React 中相互通信。我有一个大型组件应用程序。其中我有 2 个组件:ParentComponentOne 和 ParentComponentTwo。在 ParentComponentOne 中,我有一个名为 ChildParentOne 的组件。如何仅在单击 ChildParent One 时渲染 ParentComponentTwo

应用程序.jsx

import React, { Component } from 'react';
import ParentComponentOne from 'ParentComponentOne';
import ParentComponentTwo from 'ParentComponentTwo';
import './App.css';

class App extends Component {
state = {
show:{
componentTwo: false
}
};

render() {
return (
<div>
<ParentComponentOne />
{this.state.show.componentTwo? <ParentComponentTwo /> : null}
</div>
);
}
}

export default App;

ParentComponentOne.jsx

import React, { Component } from 'react';
import ChildParentOne from 'ChildParentOne';

class ParentComponentOne extends Component {

render() {
return (
<div>
<ChildParentOne />
<div>some content</div>
<ChildParentOne />
</div>
);
}
}
export default ParentComponentOne ;

ChildParentOne.jsx

import React, { Component } from 'react';

class ChildParentOne extends Component {

render() {
return (
<div onClick={}>
BTN
</div>
);
}
}
export default ChildParentOne ;

最佳答案

将回调传递给 ParentComponentOne,当它的子级被点击时,它将改变 show.componentTwo 状态:

class App extends Component {
state = {
show: {
componentTwo: false
}
};

childClicked() {
this.setState({
show: {
componentTwo: true
}
})
}

render() {
return (
<div>
<ParentComponentOne childClicked={this.childClicked} />
{this.state.show.componentTwo? <ParentComponentTwo /> : null}
</div>
);
}
}

父组件一:

class ParentComponentOne extends Component {

render() {
return (
<div>
<ChildParentOne onBtnClick={this.props.childClicked} />
<div>some content</div>
<ChildParentOne onBtnClick={this.props.childClicked} />
</div>
);
}
}

现在,只需将此回调类似地传递给 ChildParentOne 并将其用作 prop:

class ChildParentOne extends Component {

render() {
return (
<div onClick={this.props.onBtnClick}>
BTN
</div>
);
}
}

关于javascript - React - 单击不是其子组件的组件时呈现组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43628434/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com