首页 > 解决方案 > 将 this.function.bind(this) 替换为函数组件

问题描述

我有一个看起来像这样的类组件:

interface MyProps {
  addingCoord: any
  resetCoords: any
}

interface MyState {
  x: any
  y: any
}

class DrawerOld extends React.Component<MyProps, MyState> {
  width: number
  height: number

  constructor(props: MyProps) {
    super(props)
    this.state = {x: NaN, y: NaN, hoverMode: false}
    this.width = this.height = 400
  }

  onMouseMove(e: React.MouseEvent<HTMLDivElement, MouseEvent>) {
    this.setState(
      {
        x: parseFloat((e.nativeEvent.offsetX / this.width).toFixed(3)),
        y: parseFloat(
          ((this.height - e.nativeEvent.offsetY) / this.height).toFixed(3),
        ),
      },
      () => {
        if (this.state.hoverMode) this.addCoord()
      },
    )
  }

  toggleHoverMode() {
    this.setState({hoverMode: !this.state.hoverMode})
  }

  addingCoord() {
    const coord = {x: this.state.x, y: this.state.y}
    this.props.addingCoord(coord)
  }

  render() {
    return (
      <div>
        <div>
          <div
            onMouseMove={(e) => this.onMouseMove(e)}
            onClick={this.addCoording.bind(this)}
          />
        </div>
      </div>
    )
  }
}

export default DrawerOld

我想把它修改成一个功能组件。但是,我无法弄清楚如何准确地修改这部分: onClick={this.addCoord.bind(this)}

因为目前如果我使用onClick={props.addCoord()},我会在使用时遇到如下错误:

TypeError:无法读取未定义的属性“x”

<DrawerNew addCoord={this.addCoord.bind(this)}
                            resetCoords={this.resetCoords.bind(this)} />

标签: javascriptreactjstypescriptreact-nativereact-functional-component

解决方案


改变你的onClick

由此

onClick={props.addCoord()}

对此

onClick={addCoord}

推荐阅读