我有一个表,显示用户选择的项目。现在,当用户添加项目时,该项目将作为新行添加。我尝试更改它,以便与其增加新行,而不是增加新行。但是,此操作不起作用,因为我收到一个错误消息,说在:
之后还需要一个其他代码。
<table>
<thead>
<tr>
<th>Item</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
{this.state.basket.map(item => {
return (
{this.getAmount(item) === 0 ? (
<tr>
<td>{item}</td>
<td>{this.getAmount(item)}</td>
</tr>
) : (
this.updateAmount(item);
)
)
})}
</tbody>
</table>
我将如何更改它以使其在项目旁边带有amount
?
获取金额方法:
getAmount = item => {
var amount = 0;
var basket = [...this.state.basket];
basket.forEach(i => {
if (i === item) {
amount++;
}
});
console.log(item + " : " + amount);
return parseInt(amount);
};
更新金额方法:
updateAmount = item => {
return this.getAmount(item);
};
答案 0 :(得分:0)
我是React的新手,但是看起来您在“ else”中调用的方法只是返回一些值,而不是jsx。您的“ if”结果返回的是jsx,但是您其他的结果只是调用了一个仅返回值的函数。
getAmount = item => {
var amount = 0;
var basket = [...this.state.basket];
basket.forEach(i => {
if (i === item) {
amount++;
}
});
console.log(item + " : " + amount);
return (
<React.Fragment>
<span>{parseInt(amount)}</span>
</React.Fragment>
)
};
自从我刚开始学习React以来,我很有可能会离开,但我认为如果有帮助的话,值得一试。或者,您可能可以直接在其他地方执行<React.Fragment>
部分,并将函数放在<span>
内,但不确定是否可行。