在另一个组件中响应 JS 调用函数

React JS call function within another component

我正在尝试使用 Mousetrap 库从 React 中的另一个组件调用一个函数。

class Parent extends React.Component {
    constructor() {
      super();

    } 
    ...
    render() {
      return(...);
    }
}
class Child extends React.Component {
    constructor() {
      super();
      this.state = { show: false };
      this.open = this.open.bind(this);
      this.close = this.close.bind(this);
    }
    open() {
      this.setState({ show: true });
    }
    close() {
      this.setState({ show: true });
    }
    render() {
      return(...);
    }
}

现在,我想做的是在父级中的某处调用 Mousetrap.bind('e', function(e) { Child.open() });(因为父级将被渲染,而子级将仅在此命令上渲染)。但是,我不确定在哪里实际包含它。在构造函数中调用它会更好,还是在 render() 的某个地方,或者我没有考虑过的其他地方?

最好将其作为您所在州的一部分,例如

class Parent extends React.Component {
  constructor(){
    super();
    this._eKeyPress = this._eKeyPress.bind(this);
    this.state.showChild = false;
  }
  componentDidMount(){
    Mousetrap.bind('e', this._eKeyPress);
  }
  componentWillUnmount(){
    Mousetrap.unbind('e', this._eKeyPress);
  }
  _eKeyPress(){
    this.setState({showChild: true});
  }

  render(){
    return <Child show={this.state.showChild} />;
  }
}

之后的下一个问题是您是否需要创建 child,因为您也可以创建

render(){
  return this.state.showChild ? <Child /> : null;
}