React: Retrieve dynamic child key upon event

前端 未结 2 658
小鲜肉
小鲜肉 2021-02-05 05:39

I am aware that dynamic children of a component must have a unique key as the following (modified example from official docs):



        
相关标签:
2条回答
  • 2021-02-05 06:07

    Partially apply the function callback by using JavaScript's native bind. This is mentioned in React's "Communicate Between Components" doc:

    callbackFn: function(key) {
      // key is "result.id"
      this.props.callbackFn(key);
    },
    render: function() {
      var results = this.props.results;
      return (
        <div>
          {results.map(function(result) {
            return (
              <ChildComponent type="text" key={result.id}
                changeCallback={this.callbackFn.bind(this, result.id)} />
            );
          }, this)}
        </div>
      );
    }
    
    0 讨论(0)
  • 2021-02-05 06:13

    Although the first answer is correct this is considered as a bad practice since:

    A bind call or arrow function in a JSX prop will create a brand new function on every single render. This is bad for performance, as it will result in the garbage collector being invoked way more than is necessary.

    Better way:

    var List = React.createClass({
      handleClick (id) {
        console.log('yaaay the item key was: ', id)
      }
    
      render() {
        return (
          <ul>
            {this.props.items.map(item =>
              <ListItem key={item.id} item={item} onItemClick={this.handleClick} />
            )}
          </ul>
        );
      }
    });
    
    var ListItem = React.createClass({
      render() {
        return (
          <li onClick={this._onClick}>
            ...
          </li>
        );
      },
      _onClick() {
        this.props.onItemClick(this.props.item.id);
      }
    });
    

    Source: https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-bind.md

    0 讨论(0)
提交回复
热议问题