我试图让React与ES6语法配合使用。在ES5中,我没有构造函数而是使用函数绑定语法并设置了setInitialState,这可以正常工作。我有一个价格列表,其中价格是任意的,当输入元素改变时我希望状态(state)也发生变化。但必须改变正确的价格。
我甚至不确定这是否是正确的做法。请有人告诉我应该如何实现最新的方式?
以下是我的代码:
import React, {Component} from 'react'
import 'bootstrap/dist/css/bootstrap.css';
export default class PriceTable extends Component {
constructor(props, context) {
super(props, context);
this.state = {
pid: this.props.pid || "12345",
name: this.props.name || "name",
prices: this.props.prices || [
{count: 1, desc: 'one', price: 8.25},
{count: 6, desc: 'six', price: 7.60},
{count: 12, desc: 'twelve', price: 6.953}
]
};
this.setPid = this.setPid.bind(this);
this.setName = this.setName.bind(this);
this.setCount = this.setCount.bind(this, i);
this.setDesc = this.setDesc.bind(this, i);
this.setPrice = this.setPrice.bind(this, i);
this.logDebug = this.logDebug.bind(this);
}
setPid(e) {
this.setState({pid: e.target.value})
}
setName(e) {
this.setState({name: e.target.value})
}
setCount(i, e) {
var newPrices = this.state.prices
newPrices[i].count = e.target.value
this.setState({prices: newPrices})
}
setDesc(i, e) {
var newPrices = this.state.prices
newPrices[i].sec = e.target.value
this.setState({prices: newPrices})
}
setPrice(i, e) {
var newPrices = this.state.prices
newPrices[i].price = e.target.value
this.setState({prices: newPrices})
}
_renderPriceRow(price, i) {
return (
<tr key={i}>
<td >
<input type="text" className="form-control" defaultValue={price.count} onChange={this.setCount(this, i).bind(this, i)}/>
</td>
<td >
<input type="text" className="form-control" defaultValue={price.desc} onChange={this.setDesc(this, i).bind(this, i)}/>
</td>
<td >
<input type="text" className="form-control" defaultValue={price.price} onChange={this.setPrice(this, i).bind(this, i)}/>
</td>
</tr>
);
}
render() {
return (
<div className="row">
...
</div>
);
}
}
这是错误信息...
PriceTable.jsx:21 Uncaught ReferenceError: i is not defined
at new PriceTable (PriceTable.jsx:21)
Uncaught TypeError: Cannot read property 'setCount' of undefined at _renderPriceRow
- Dennis Ichthis
作为引用来调用setCount
函数,如果你不绑定它,函数内的this
将指向函数本身的上下文。这与绑定其他使用setState
的函数类似。 - Shubham Khatri