我正在使用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! …Run Code Online (Sandbox Code Playgroud) 根据标题,为什么最初的this.props失败?实际上,如果您依赖构造函数中的props,该如何解决呢?例如,我想在订阅中引用道具吗?
class AboutBox extends Component {
static defaultProps = {
title: 'Undefined Product',
}
constructor() {
super();
console.log(this.props.title); //this fails (=> null)
}
render() {
console.log(this.props.title); //this works (=> 'Undefined Product')
return null;
}
}
Run Code Online (Sandbox Code Playgroud)