繁体   English   中英

如何通过引用组件添加Click Handler

[英]How to add Click Handler through reference of component

我正在学习React js,并且想知道,可以通过引用组件来添加点击处理程序。

我尝试了以下操作,但没有成功

import React, { Component } from 'react'

export default class RefsDemo extends Component {
  constructor(props) {
    super(props)

    this.inputRef=React.createRef();
    this.buttonRef=React.createRef();
  }

  componentDidMount()
  {
      console.log(this.buttonRef);
      this.buttonRef.current.onClick=()=>this.abchandle()
  }

  abchandle()
  {
      alert('hi');
  }

    render() {
    return (
      <div>
        <button ref={this.buttonRef} >click</button>
      </div>
    )
  }
}

this.buttonRef.current是DOM节点,不是this.buttonRef.current组件,因此要定义onclick处理程序,应定义onclick (注意小写c ): this.buttonRef.current.onclick=()=>this.abchandle()

https://codepen.io/liboul/pen/jRJmqZ

我相信我们需要使用ref来选择节点,然后添加一个事件列表器,如下所示:

我们需要导入“ react-dom”以使其起作用

import ReactDOM from 'react-dom'

然后添加这段代码-:

componentDidMount()
  {
      let domNode = ReactDOM.findDOMNode(this.buttonRef.current);
      if(domNode) {
        domNode.addEventListener('click', () => console.log('click'));
      }
  }

希望对您有所帮助。...顺便说一句,当我们可以在JSX中执行类似的操作时,为什么需要附加点击处理程序

<button onClick={() => console.log('click')} >Click</button>

可以看到这个

https://stackblitz.com/edit/react-zakgqb?file=Hello.js

通过onClick属性可以实现您要执行的操作,这是实现此任务的最佳实践。

因此在button元素内部只需添加一个onClick属性,如下所示:

<button onClick={this.abchandle}>click</button>

没有理由为此使用添加事件侦听器,这不是反应方式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM