I am trying to use componentenet details to call an action in the submit event handler with a short form of 6.1.1, but in the event handler function I get "this" is undefined. that's what I'm doing:
"this" is undefined
class ForgetPasswordForm extends Component { xubmit (values) { console.log(this); } render() { const { handleSubmit } = this.props; return ( <form onSubmit={ handleSubmit(this.xubmit) }> ... ); }; }
I also tried () => handleSubmit(this.xubmit.bind(this))and this.xubmit.bind(this), as mentioned in React: this is null in the event handler , but none of them worked.
() => handleSubmit(this.xubmit.bind(this))
this.xubmit.bind(this)
More on my setup:
handleSubmit.bind(this.xubmit)thus inside handleSubmit, thispoints to this.xubmit.
handleSubmit.bind(this.xubmit)
handleSubmit
this
this.xubmit
, .
. JavaScript
handleClick, , , handleClick (fn) { fn() }, fn. . - , :
handleClick
handleClick (fn) { fn() }
fn
onSubmit={this.props.handleSubmit.bind(this.props.context, this.xubmit.bind(this))}
ForgetPasswordForm handleSubmit , this.xubmit this, undefined.
ForgetPasswordForm
undefined
class ForgetPasswordForm extends Component { xubmit = (values) => { console.log(this); } }
,
<form onSubmit={handleSubmit((values) => this.xubmit(values)) }>
you must use class properties and arrow function together
class properties are part of stage-2
class ForgetPasswordForm extends Component { xubmit = (values) => { console.log(this); } render() { const { handleSubmit } = this.props; return <form onSubmit={ handleSubmit(this.xubmit) }>; }; }
Function with arrow thisfor function
Source: https://habr.com/ru/post/1660145/More articles:No module named __future__ - pythonSQL Server MERGE without source table - mergeCreating an ajax search function - javascriptAWS SSL for EC2 instance without load balancing - NodeJS - node.jsHow to use Twilio Client in Angular 2? - angularHow to manage code for different designs to support all devices - androidResize EditText (any view) shown in alertBox? - javaPandas Group By and Score - pythoncannot select file in file manager using OkHttp3 - androidInsert and sort in ascending order - javaAll Articles