The Ant Design Table component customizes the scope of render to solve the problem of not finding this.

I ran into a problem with Ant Design Table today. When I was customizing colunm’s render function, I couldn’t find the state in this.state.

Let’s repeat it briefly:

class Demo extends React.Component {
  state = {
    action: 'delete'.columns: [{title: 'Action'.key: 'action'.render: this.renderAction,
      },
    ],
  };

  renderAction() {
    // State cannot be found
    return <a>{this.state.delete}</a>;
  }
  
  // ...

	render() {
    return <Table columns={columns} dataSource={this.data} />; }}Copy the code

This is because the Column Render function renders a child component, meaning that this in the renderAction is no longer pointing to the Demo, but to the current render element.

Therefore, you can use JavaScript’s bind method to bind the state to renderAction.

 columns: [
      {
        title: 'Action'.key: 'action'.render: this.renderAction.bind(this),  // Change here},].Copy the code

Alternatively, you can use the arrow function, which can be written more concisely using the scoped nature of the arrow function:

 columns: [
      {
        title: 'Action'.key: 'action'.render: () = >{return this.renderAction()},  // Change here},].Copy the code

React events also have this scope problem. Here’s an example:

<Button onClick={this.onClick}/>
Copy the code

Button is bound to a click event, so how should this event be defined?

There are two ways to do it, one is to use the function definition, but the way you use the arrow function.

onClick() {
  // you code
}

onClick = () = >{}Copy the code

That makes sense, but what if I need to pass an argument to onClick? How should onClick be defined?

<Button onClick={this.onClick(index)}/>
Copy the code

First, we need to understand that the onClick in a Button accepts an event, which is a function, so we need to return a function when we define the onClick event.

onClick (index) {
  return function() {
    // your code
  }
}

onClick = index= > () = >{}Copy the code

Why do arrow functions have two arrows? This. OnClick points to the function itself. If you use an arrow, you do not return the function object, but the contents of the function, so you need to wrap another arrow function.

And obviously, the arrow function looks much clearer.

It’s messy, just for the record.