reactjs – 为什么我不能将React唯一键传递给onChange方法
发布时间:2020-12-15 09:32:02 所属栏目:百科 来源:网络整理
导读:我正在使用React ES6.我正在渲染一个包含唯一鱼元素的库存清单,每个鱼元素都映射到一个唯一的键并从父组件继承道具.我希望能够编辑鱼文本并将此更改输入到父状态. 我的代码不起作用,因为关键道具不可用于onChange处理程序.大多数在线文档都建议使用ReactLink
我正在使用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> ) } 映射键并将它们传递给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> ) } HandleChange无法记录密钥 handleChange(event,key){ console.log("the change handler is now firing and the key is" + key); } 解决方法
您应该将事件回调包装为函数或使用.bind
<input type="text" value={ nameOfFish } onChange={ (e) => this.handleChange(e,key) } /> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |