gpt4 book ai didi

javascript - 如何从动态添加的字段中获取差异 - React

转载 作者:行者123 更新时间:2023-12-01 01:23:10 25 4
gpt4 key购买 nike

我是 Reactjs 新手。我想做的就是如下:

我有三个字段:ENTRY、EXIT、TOTAL

TOTAL = EXIT - ENTRY

示例:

进入 |退出 |总计

1 | 2 | 1

2 | 4 | 2

3 | 6 | 3

5 | 10| 5

此处的 ENTRY 和 EXIT 是单击“+添加”按钮时动态添加的字段。我已经能够动态添加字段,但没有获得 TOTAL 值。

var entry;
var exit;
class Calculator extends React.Component {
state = {
values: [{id:0,exit:0,entry:0}],
total:[]
};

add() {
this.setState(prevState => prevState.values.push(null));
}
changeVal(val, index, key) {
if(key == 'exit'){
exit = val;
}else{
entry =val;
}
this.setState(prevState => (prevState.values[index] = {id:index, exit:val, entry: val}));
}
getTotal() {
let total = 0;
for (let i = 0; i < this.state.values.length; i++) {
if (this.state.values[i] !== null) {
total = this.state.values[i].exit - this.state.values[i].entry;
}
}
return total;
}

render() {
return (
<div>
{this.state.values.map((val, index, key) => (
<div key={index}>
<input
onChange={e => this.changeVal(e.target.value, index, 'exit')}
name={ `exit[${index}]` }
type="number"
value={val}
placeholder="Enter a value"
/>
<input
onChange={e => this.changeVal(e.target.value, index, 'entry')}
name={ `entry[${index}]` }
type="number"
value={val}
placeholder="Enter a value"
/>
<input
name={ `total[${index}]` }
type="number"
value={this.state.total}
/>
</div>
))}
<button onClick={this.add.bind(this)}> +Add</button>
</div>
);
}
}
ReactDOM.render(<Calculator /> , document.getElementById('calculator'));

另请告诉我这是否是动态添加输入字段的最佳方法。谢谢

最佳答案

你可以这样做:

var entry;
var exit;
class Calculator extends React.Component {
state = {
values: [{ id: 0, exit: 0, entry: 0 }],
total: []
};

add() {
let { values } = this.state;
values.push({ id: 0, exit: 0, entry: 0 });
this.setState({ values });
}

changeVal(val, index, key) {
let { values } = this.state;
values[index][key] = val;
this.setState({ values });
}

getTotal(data) {
return Number(data.exit) - Number(data.entry);
}

render() {
let { values, total } = this.state;
return (
<div>
{values.map((val, index, key) => {
return (
<div key={index}>
<input
onChange={e => this.changeVal(e.target.value, index, "exit")}
name={`exit[${index}]`}
type="number"
value={val.exit}
placeholder="Enter a value"
/>
<input
onChange={e => this.changeVal(e.target.value, index, "entry")}
name={`entry[${index}]`}
type="number"
value={val.entry}
placeholder="Enter a value"
/>
<input
name={`total[${index}]`}
type="number"
value={this.getTotal(val)}
/>
</div>
);
})}
<button onClick={this.add.bind(this)}> +Add</button>
</div>
);
}
}

这里是直播demo

希望有帮助:)

关于javascript - 如何从动态添加的字段中获取差异 - React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54068807/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com