我试图弄清楚如何让组件在React中相互通信。我有一个大型组件App。在其中我有2个组件:ParentComponentOne和ParentComponentTwo。在ParentComponentOne中,我有一个名为ChildParentOne的组件。如何仅在单击ChildParent One
时呈现ParentComponentTwoApp.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 ;
答案 0 :(得分:1)
将回调传递给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>
);
}
}
ParentComponentOne:
class ParentComponentOne extends Component {
render() {
return (
<div>
<ChildParentOne onBtnClick={this.props.childClicked} />
<div>some content</div>
<ChildParentOne onBtnClick={this.props.childClicked} />
</div>
);
}
}
现在,只需将此回调传递给ChildParentOne
,并将其用作道具:
class ChildParentOne extends Component {
render() {
return (
<div onClick={this.props.onBtnClick}>
BTN
</div>
);
}
}