javascript - 将 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)} />
解决方案
改变你的onClick
由此
onClick={props.addCoord()}
对此
onClick={addCoord}
推荐阅读
- html - Responsivity Misconfiguration
- docker - 无法读取 dockerfile - .NET 5.0
- javascript - 将 JavaScript 对象转换为浮点数
- angular - 部分不区分大小写的角度重定向
- c - 在c中创建一个管道数组
- puppet - 木偶不卸载包
- javascript - 设计当鼠标移过视频时间线时出现的最小化图片的问题
- powershell - PS1 Start-Process script error - Cant run document in the middle of pipeline
- javascript - 如果按下按钮时值超出范围,则显示错误警报
- django - 提高 Python Tesseract OCR 的准确性