首页 > 解决方案 > 作为道具传递的反应元素的反应参考,动态事件

问题描述

我正在构建一个下拉组件,它获取一个按钮元素作为道具。这是对我正在尝试做的事情的简短描述:

class Dropdown extends React.Component {
   render() {
     let button = this.props.trigger;
     // How do I get a ref to the button native DOM node?
     // How can I attach a react event to the button?

   }
}

这就是我想使用它的方式:

class App extends React.Component {
   render() {
     return (
          <Dropdown trigger={<button>Click me</button>}>
               dropdown content
          </Dropdown>
    )
   }
}

简而言之,如果我有一个带有反应元素的变量,
1.如何获得作为道具传递的按钮 dom 节点的引用?(我需要将其传递给dom-align)。
2. 如何将事件侦听器附加到传递的按钮元素?

标签: javascriptreactjsreact-component

解决方案


这就是您可以使用按钮的箭头功能组件并传递 ref 和事件侦听器的方法。

const Button = ({buttonRef, onEvent}) => <button ref={buttonRef} onEvent />

class Parent extends Component {
  methodForButton = e => {...}
  render() {
    return (
      <Dropdown
        propButton={
         <Button buttonRef={el => this.buttonElement = el} onEvent={this.methodForButton} />
        }
      >{...}<Dropdown />
    );
  }
}

您也可以将按钮作为孩子而不是道具传递

<Dropdown><Button /><Dropdown />

推荐阅读