如何从父级单击子元素

时间:2017-12-28 13:56:37

标签: reactjs

我有两个组成部分:
Parent.js

export default class Parent extends React.Component {
  handleTagHierClick(e) {
    var excel = this.refs.workbook;
    excel.click();
  }

  render() {
    return (
      <button onClick={(e) => this.handleTagHierClick(e)} className="btn btn-default btn-block">Download Tag Hier</button>
      <Child/>
    )
  }
}

Child.js

import React from 'react';

export default class Child extends React.Component {
  render() {
    return (
      <div ref='workbook'></div>
    )
  }
}

当我点击div组件中的Child元素时,如何触发button组件中Parent元素的点击?我尝试使用ref但由于元素位于不同的组件上而无法工作......

2 个答案:

答案 0 :(得分:1)

如果我理解你的话,你可以这样做

class Parent extends React.Component {

 handleTagHierClick(e) {
     this.child.someMethod();
 }

  render() {
    return (<div>
      <Child ref={(obj) => { this.child = obj; }}/>
      <button
         onClick={(e) => this.handleTagHierClick(e)}/>
      </div>
    );
  }
}

孩子内部

import React from 'react';

export default class Child extends React.Component {
  someMethod(){
      // Here you can trigger click on the div
      this.div.click();
  }
  render() {
    return (
      <div  ref={(obj) => { this.div = obj; }}></div>
    )
  }
}

答案 1 :(得分:0)

您是否尝试在按钮上添加引用?

<button ref='myButton'...

然后将变量excel替换为:

var excel = this.refs.myButton.refs.workbook;