欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

React学习记录——ref

程序员文章站 2022-07-03 09:02:20
...
import React from 'react'
import classNames from 'classnames'
interface State {
  count: number,
  className: string
}

interface Prop {

}

export default class ReButton extends React.Component<Prop, State> {
  myRef: any
  constructor(props: any) {
    super(props)
    this.add = this.add.bind(this)
    this.myRef = React.createRef<any>()
    this.state = {
      count: 0,
      className: ''
    }
  }

  add(e: any) {
    e.preventDefault()

    let className = classNames({
      "re-button": this.state.count % 2 === 1
    })
    this.setState({
      count: this.state.count + 1,
      className: className
    })
    console.log(this.myRef)
  }




  render() {

    return (
      <div>
        <button ref={this.myRef} className={this.state.className} onClick={this.add}>测试</button>
        <div>
          {this.state.count}
        </div>
      </div>

    )
  }
}

输出:
React学习记录——ref

相关标签: typescript