React:在事件时检索动态子键 [英] React: Retrieve dynamic child key upon event

查看:52
本文介绍了React:在事件时检索动态子键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道组件的动态子级必须具有唯一 key 如下(官方文档中的修改示例):

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

render: function() {
  var results = this.props.results;
  return (
    {results.map(function(result) {
      return <ChildComponent type="text" key={result.id} changeCallback={this.props.callbackFn}/>;
    })}
  );
}

考虑到 ChildComponent 是嵌套在这里的另一个React组件,如下所示 render 方法

Considering that ChildComponent is another React component nested here, with a render method as bellow

render: function() {
  var results = this.props.results;
  return (
    <div className="something">
       <input type="text" onChange={this.props.changeCallback} />
    </div>
  );
}

有什么方法可以在 callbackFn时访问密钥(事件)被调用?

is there any way to access the key when callbackFn(event) is called?

推荐答案

使用JavaScript的原生 bind 。在React的组件间通信中提到了这一点:doc:

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>
  );
}

这篇关于React:在事件时检索动态子键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆