如何在实例化时 link 一起 React child 和 parent 组件?

How to link together React child and parent components when instantiating them?

我有两个组件,TopBarItemMenu,它们是嵌套的并且具有 "if the menu is open, the top bar should not show the tooltip" 的功能。我想像这样将它们连接在一起:

<TopBarItem tooltip="Settings">
  <Menu onOpen={parent.tooltipOff} onClose={parent.tooltipOn}>…</Menu>
</TopBarItem>

这在 JSX / React 中可行吗?也很高兴下降到 JS,但如果可能的话更愿意保留 JSX。

另一个选项(来自已删除的答案)是将两个组件包装在第三个祖父母中,该祖父母保持 tooltipEnabled 状态并通过 属性 将其传递给 TopBarItem。虽然这是完全可以接受的,但如果可能的话,我更愿意直接切换 TopBarItem 中的状态,而不是通过祖父母。

按照以前删除的答案建议的实施方式进行。如果有人知道,将接受更简洁的解决方案。

export class TopbarMenuItem extends Component {
  state: {
    tooltipEnabled: bool
  }
  tooltipOn: () => null;
  tooltipOff: () => null;

  constructor(props: Object) {
    super(props);
    this.state = {
      tooltipEnabled: true
    }
    this.tooltipOn = this.tooltipOn.bind(this);
    this.tooltipOff = this.tooltipOff.bind(this);
  }

  tooltipOff() {
    this.setState({tooltipEnabled: false});
  }

  tooltipOn() {
    this.setState({tooltipEnabled: true});
  }

  render() {
    return (
      <TopbarItem tooltip={this.state.tooltipEnabled ? this.props.tooltip : ''}>
        <Menu onOpen={this.tooltipOff} onClose={this.tooltipOn}>
          {this.props.children}
        </Menu>
      </TopbarItem>
    );
  }
}