JSX props should not use .bind ()

How to fix this error when I have a binding in this way: earlier binding to the constructor has been solved, but for me it is a bit complicated:

{this.onClick.bind(this, 'someString')}> and <form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}> 
+6
source share
2 answers

Option 1:

Use arrow functions (with babel plugins) PS: - Experimental function

 class MyComponent extends Component { handleClick = (args) => () => { // access args here; // handle the click event } render() { return ( <div onClick={this.handleClick(args)}> ..... </div> ) } } 

Option 2: Not Recommended

Define the functions of arrows in the render

  class MyComponent extends Component { render() { const handleClick = () => { // handle the click event } return ( <div onClick={handleClick}> ..... </div> ) } } 

Option 3:

Use binding in constructor

  class MyComponent extends Component { constructor() { super(); this.handleClick = this.handleClick.bind(this); } handleClick() { // handle click } render() { return ( <div onClick={this.handleClick}> ..... </div> ) } } 
+14
source

I recommend using binding in the constructor of the class. This will avoid inline repetition (and confusion) and will only β€œbind” once (when the component is triggered).

Here is an example of how you can achieve cleaner JSX in your use case:

 class YourComponent extends React.Component { constructor(props) { super(props); // Bind functions this.handleClick = this.handleClick.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleClick() { this.onClick('someString'); } onClick(param) { // That your 'onClick' function // param = 'someString' } handleSubmit() { // Same here. this.handleFormSubmit(); } handleFormSubmit() { // That your 'handleFormSubmit' function } render() { return ( <form onSubmit={this.handleSubmit}> <p>...</p> <button onClick={this.handleClick} type="button">Cancel</button> <button type="submit">Go!</button> </form> ); } } 
+3
source

Source: https://habr.com/ru/post/1012599/


All Articles