I have a class component that looks like this:
JavaScript
x
59
59
1
interface MyProps {
2
addingCoord: any
3
resetCoords: any
4
}
5
6
interface MyState {
7
x: any
8
y: any
9
}
10
11
class DrawerOld extends React.Component<MyProps, MyState> {
12
width: number
13
height: number
14
15
constructor(props: MyProps) {
16
super(props)
17
this.state = {x: NaN, y: NaN, hoverMode: false}
18
this.width = this.height = 400
19
}
20
21
onMouseMove(e: React.MouseEvent<HTMLDivElement, MouseEvent>) {
22
this.setState(
23
{
24
x: parseFloat((e.nativeEvent.offsetX / this.width).toFixed(3)),
25
y: parseFloat(
26
((this.height - e.nativeEvent.offsetY) / this.height).toFixed(3),
27
),
28
},
29
() => {
30
if (this.state.hoverMode) this.addCoord()
31
},
32
)
33
}
34
35
toggleHoverMode() {
36
this.setState({hoverMode: !this.state.hoverMode})
37
}
38
39
addingCoord() {
40
const coord = {x: this.state.x, y: this.state.y}
41
this.props.addingCoord(coord)
42
}
43
44
render() {
45
return (
46
<div>
47
<div>
48
<div
49
onMouseMove={(e) => this.onMouseMove(e)}
50
onClick={this.addCoording.bind(this)}
51
/>
52
</div>
53
</div>
54
)
55
}
56
}
57
58
export default DrawerOld
59
I want to modify it into a functional component. However, I am unable to figure out how to accurately modify this part:
onClick={this.addCoord.bind(this)}
because currently if I use onClick={props.addCoord()}
, I would get errors like these upon using it:
TypeError: Cannot read property ‘x’ of undefined
JavaScript
1
3
1
<DrawerNew addCoord={this.addCoord.bind(this)}
2
resetCoords={this.resetCoords.bind(this)} />
3
Advertisement
Answer
Change your onClick
from this
JavaScript
1
2
1
onClick={props.addCoord()}
2
to this
JavaScript
1
2
1
onClick={addCoord}
2