Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6287

replace this.function.bind(this) for function component

$
0
0

I have a class component that looks like this:

interface MyProps {  addCoord: any  resetCoords: any}interface MyState {  hoverMode: any  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})  }  addCoord() {    const coord = {x: this.state.x, y: this.state.y}    this.props.addCoord(coord)  }  render() {    return (<div><div className="d-flex justify-content-center"><div            onMouseMove={(e) => this.onMouseMove(e)}            onClick={this.addCoord.bind(this)}          /></div></div>    )  }}export default DrawerOld

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

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

Viewing all articles
Browse latest Browse all 6287

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>