为什么我不能将React唯一键传递给onChange方法

ElJ*_*mes 4 ecmascript-6 reactjs

我正在使用React ES6.我正在渲染一个包含唯一鱼元素的库存清单,每个鱼元素都映射到一个唯一的键并从父组件继承道具.我希望能够编辑鱼文本并将此更改输入到父状态.

我的代码不起作用,因为关键道具不可用于onChange处理程序.大多数在线文档都建议使用ReactLink进行双向流程,但现在已弃用,所以我宁愿找到另一种解决方案.我的问题是双重的 - 在ES6反应组件中双向流的最佳模式是什么?为什么这个代码不起作用 - 具体地说为什么我不能在onChange处理程序中控制日志'key'.

非常感谢

  render () {
    var fishIds = Object.keys(this.props.fishes);
    console.log("fishes are....." +fishIds);
    return (
      <div>
      <h2>Inventory</h2>
      {fishIds.map(this.renderInventory)}
      <AddFishForm {...this.props}/>
      <button onClick={this.props.loadSamples}> Load Sample Fishes</button>
      </div>
    )
  }
Run Code Online (Sandbox Code Playgroud)

映射键并将它们传递给renderInventory

renderInventory(key) {

      var fish = this.props.fishes[key];
        console.log(fish);
        console.log("the key is" +key);
        var nameOfFish = fish.name
    return(
<div className = "fish-edit" key={key}>
<input type = "text" value ={nameOfFish} onChange={this.handleChange(key)} />
<input type = "text" value ={fish.price}/>


<select>
  <option value = "unavailable">Sold out!  </option>
  <option value = "available">Fresh!  </option>
</select>


<textarea value={fish.desc}>
</textarea>
</div>

    )

  }
Run Code Online (Sandbox Code Playgroud)

HandleChange无法记录密钥

handleChange(event, key){
console.log("the change handler is now firing and the key is" + key);

}
Run Code Online (Sandbox Code Playgroud)

Ale*_* T. 9

您应该将事件回调包装function或使用.bind

<input 
  type="text"
  value={ nameOfFish } 
  onChange={ (e) => this.handleChange(e, key) } 
/>
Run Code Online (Sandbox Code Playgroud)