React - 从Parents ComponentDidmount()调用子组件方法

时间:2018-02-12 19:48:21

标签: reactjs

我有一个父组件

    class Parent extends React {
        componentDidMount() {
            document.getElementById(this.props.grandParentElemntId).addEventListener("mouseleave",this.handleClick);
         }
        handleClick() {
            this.childcomponent2.method();
        }
         render() {
             return(
               <div>
                  <ChildComponent1 />
                      <div>
                          <ChildComponent2 ref = {(ref) => this.childcomponent2 = ref} />
                      </div>
               </div>
             );
         }
 }

我试图在挂载父组件后立即触发的mouseleave事件上调用子组件2的方法。但是由于无法访问该方法,我一直收到错误。我一直在寻找refs的反应文档,但没有找到解决这个问题的方法。有人有解决方案吗?

1 个答案:

答案 0 :(得分:0)

我建议使用state和props来处理这个而不是试图强制使用vanilla js eventlisteners:

Working JSFiddle Example

class Parent extends React.Component {
  state = {
    mouseLeft: false
  };

  componentDidMount() {

this.parent.addEventListener("mouseleave",this.handleMouseEvt.bind(this, true));

this.parent.addEventListener("mouseenter",this.handleMouseEvt.bind(this, false));
  }

  handleMouseEvt = mouseLeft => {
    this.setState({ mouseLeft });
  };

  render() {
    return(
      <div ref={ ref => this.parent = ref } className="parent">
        <p>Trigger mouseLeave on me!</p>
        <ChildComponent1 />
        <div>
          <ChildComponent2 mouseLeft={this.state.mouseLeft} ref = {(ref) => this.childcomponent2 = ref} />
        </div>
      </div>
    );
  }
 }

 class ChildComponent2 extends React.Component {
        someMethod = () => {
        alert('Did someMethod() in ChildComponent2');
    }

    componentWillReceiveProps(nextProps) {
        if(nextProps !== this.props && nextProps.mouseLeft) {
        this.someMethod();
      }
    }

        render() {
        return <div>Child 2</div>
    }
 }