React transfer parameter with arrow in child component

I have this parent and child component, I want to pass a click function to select an element in the child component. However, it seems that the function in the child component is automatically called instead of waiting until the user clicks the item. To make this clearer, here are my parent and child components

export class ParentView extends Component {
  state = {
    selectedItem: {}
  }

  handleClick = (item) => {
    alert('you click me');
    this.setState({selectedItem: item});
  } 

  render() {
    let item = { name: 'Item-1' };
    return (
      <div>
        <ChildItem item={item} handleClick={this.handleClick} />
      </div>
    );
  }
}

export class ChildItem extends Component {
  render() {
    const {item, handleClick} = this.props;
    return (
      <div>
        <a  onClick={handleClick(item)} />
      </div>
    );
  }
}

These are my components that use the arrow function to pass to the handleClickchild component, but a warning is always triggered on first rendering, without being run by the user. Any suggestion?

+8
source share
3 answers

onClick, .

, :

  • item handleClick.bind(this, item). bind , - item
  • , () => handleClick(item)

:

export class ChildItem extends Component {
  render() {
    const { item, handleClick } = this.props;

    return (
      <div>
        <a onClick={() => handleClick(item)} />
      </div>
    )
  }
}

onClick, handleClick onClick, , , .

<a onClick={handleClick(item)} />

:

@dhilt, . .bind , render ChildItem, , "" render. ], , , , , eslint, - .

1) performance problems . Array.prototype.forEach for, for "".

2) . , .

, , , , , https://cdb.reacttraining.com/react-inline-functions-and-performance-bdff784f5578

+12

: ChildItem , , ( - .bind; ). , props :

export class ChildItem extends Component {

  onClick = () => {
    this.props.handleClick(this.props.item);
  }

  render() {
    return (
      <div>
        <a  onClick={this.onClick} />
      </div>
    );
  }
}

ParentView .

+3

ES6 :

Using arrow functions =>

onClick={() => handleClick(item)}

(@havenchyk answers ES5 ).

+2
source

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


All Articles