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

Abh*_*hek 0 javascript reactjs

我正在学习 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>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*eer 5

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

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