gpt4 book ai didi

javascript - 使用 sibling 之间的数据隐藏子组件

转载 作者:行者123 更新时间:2023-11-28 16:43:52 24 4
gpt4 key购买 nike

我有一个父组件和两个子组件。 Child1 呈现文本。 Child2 有一个按钮。我需要通过按 child2 来隐藏 child1。我尝试将函数传递给子 2,但到目前为止还没有成功。 sandbox

class Parent extends React.Component {
constructor() {
super();
this.state = {
visibility: true
};
}

handleChildClick() {
this.setState({
visibility: false
});
}

render() {
const { visibility } = this.state;
if (visibility) {
return (
<div>
<ChildOne />
<ChildTwo onClick={this.handleChildClick.bind(this)} />
</div>
);
}
}
}

class ChildTwo extends Component {
render() {
return (
<div>
<button onClick={onClick}>Hide text</button>
</div>
);
}
}

最佳答案

你的两个 child 应该像

class ChildTwo extends Component {
render() {
return (
<div>
<button onClick={this.props.onClick}>Hide text</button>
</div>
);
}
}

父组件的渲染方法应该像

render() {
const { visibility } = this.state;
let firstChild=null;
if (visibility) {
firstChild=<ChildOne />
}
return (
<div>
{firstChild}
<ChildTwo onClick={this.handleChildClick.bind(this)} />
</div>
);
}

你还应该像这样定义handleChildClick,这会自动将“this”与方法绑定(bind)

  handleChildClick=()=>{
this.setState({
visibility: false
});
}

关于javascript - 使用 sibling 之间的数据隐藏子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60787399/

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