我得到了父组件和子组件(工具提示组件)。在子组件的componentdidmount中,我想向父组件添加回调函数以关闭子组件。如何从子组件向父组件添加回调函数。
export default class Parent extends React.Component {
constructor(){
super();
}
render() {
<div>
sdf adfa sfdsf
saf
a sfdsaf sfsf safdsa
asdf safdsaf safdsafasdf
asdf safdsafdsafsadf
asdf asfsadfdsafdsaf
..............
<Child />
</div>
}
}
export default class Child extends React.Component {
constructor(){
super();
this.state = {
IsShownTooltip: false
}
}
componentDidMount = () => {
//want to add Parent div on click here to close popup with setstate
}
onClick = () => {
this.setState({
IsShownTooltip: true
});
}
render() {
<div onClick={this.onClick}>
{this.state.IsShownTooltip &&
<div>tooooooooooooooooltip text hererrrrrrrrrr</div>
}
</div>
}
}
答案 0 :(得分:1)
您可以像这样在“父”组件中执行“显示/隐藏”切换功能。
1.Parent.js
import React, { Component } from 'react';
import Child from './Child';
export default class Parent extends Component {
constructor(props){
super(props);
this.state = {
IsShownTooltip: false
}
}
onClickToggle = () => {
this.setState({
IsShownTooltip: !this.state.IsShownTooltip,
})
}
render() {
return(
<div>
parent
..............
<button onClick={() => this.onClickToggle()}>click</button>
<Child IsShownTooltip={this.state.IsShownTooltip} onClickChild={() => this.onClickToggle()} />
</div>
)
}
}
Child.js
import React, { Component } from 'react';
export default class Child extends Component {
render() {
return(
<div onClick={this.onClick}>
<button onClick={() => this.props.onClickChild()}>click</button>
{this.props.IsShownTooltip &&
<div>tooooooooooooooooltip text hererrrrrrrrrr</div>
}
</div>
)
}}
代码可以进行很多改进,仅针对您提供的示例的输出,我就是这样写的。 希望这对您有所帮助:)