【发布时间】:2018-11-07 06:15:38
【问题描述】:
how do i change the state of parent in child component
I'm trying to create a popover in react
Parent component
class App extends Component {
constructor(props) {
super(props);
this.state = {
status: false,
anchorEl: null
};
}
showpop = () => {
this.setState({ status: !this.state.status });
};
render() {
return (
<React.Fragment>
<p id="popup" onClick={this.showpop}>
Click me
</p>
{this.state.status ? (
<Popup status={this.state.status}>test</Popup>
) : (
""
)}
</React.Fragment>
);
}
}
我只是将 status 的状态传递给 popover 组件。 这是子组件
export default class popup extends Component {
constructor(props) {
super(props);
this.state = {
popupStatus: false
};
}
componentWillMount() {
document.addEventListener("click", this.handleclick, false);
}
componentWillUnmount() {
document.removeEventListener("click", this.handleclick, false);
}
handleclick = e => {
if (this.node.contains(e.target)) {
return;
} else {
//这里怎么办?
}
};
render() {
return (
<React.Fragment>
<Mainbox
status={this.props.status}
ref={node => {
this.node = node;
}}
>
{this.props.children}
</Mainbox>
</React.Fragment>
);
}
}
在handleclick函数的其他部分, 我试过这些 我将节点样式显示更改为无,但在窗口中需要单击两次才能显示弹出框
您可以看到子组件中的 Mainbox 组件是使用 styed 组件库创建的
有没有办法隐藏元素并改变父状态?
【问题讨论】:
-
您可以将更新状态的方法作为道具传递给孩子并从那里调用它。
-
请解释一下我已经尝试通过该方法但如何更改状态
标签: reactjs