0

我正在尝试使用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(),或者我没有考虑过的其他地方?

4

1 回答 1

3

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

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} />;
  }
}

之后的下一个问题是您是否需要创建孩子,因为您也可以这样做

render(){
  return this.state.showChild ? <Child /> : null;
}
于 2015-07-16T03:24:25.920 回答