gpt4 book ai didi

javascript - React - 循环输入并获取总和值

转载 作者:行者123 更新时间:2023-11-28 16:46:08 24 4
gpt4 key购买 nike

我试图在 React JS 中获取一组输入的总和,并将它们的总值总和放入 div 标签中。

每当用户输入任何输入时,我都会尝试运行此事件

问题是我确信 React 有一个正确的方法来做到这一点!

这是我微弱的尝试(请放轻松 - 我是编码新手:)

HTML

<input type="number" id="comp1" name="comp1" onChange={this.handleTotal} />
<input type="number" id="comp2" name="comp2" onChange={this.handleTotal} />
<input type="number" id="comp3" name="comp3" onChange={this.handleTotal} />
<input type="number" id="comp4" name="comp4" onChange={this.handleTotal} />
<input type="number" id="comp5" name="comp5" onChange={this.handleTotal} />
<input type="number" id="comp6" name="comp6" onChange={this.handleTotal} />
<div id=total></div>

JS

handleTotal = e => {  
// Grab all inputs that start with ID 'comp'
let inputs = document.querySelectorAll('[id^="comp"]');

// Trying to loop through the values and get the sum of all inputs
for (var i = 0; i < inputs.length; i++) {
let totalVal = inputs[i].value
console.log(totalVal);
}

//Trying to grab total values of all inputs and put in element
document.getElementById('total').innerHTML = totalVal;
}

最佳答案

目前您没有使用任何 React 的数据绑定(bind)。

最佳使用React's state保存 total 和所有 comp 输入的值。

我还使用过 .reduce方法来计算每个输入字段值的总计。但是您可以使用 for 循环实现同样的效果。

JSFiddle: Alternative "calculateTotal" function with for loop

More information on Input handling in React

class App extends React.Component {
constructor() {
super();
this.state = {
total: 0,
numbers: {
comp1: 1,
comp2: 0,
comp3: 4,
comp4: 0,
comp5: 0,
comp6: 0
}
};
}

componentDidMount() {
// Calculates the total after component is mounted
this.setState({ total: this.calculateTotal(this.state.numbers) });
}

calculateTotal = (numbers) => {
return Object.entries(numbers).reduce((finalValue, [key, value]) => {
if (value === "") {
// if entered value is empty string "", omits it
return finalValue;
}
return finalValue + value;
}, 0);
}

handleTotal = (e) => {
const { value, name } = e.target; // gets the name and value from input field
const parsedValue = value === "" ? "" : parseFloat(value); // parses the value as a number or if empty treats it as empty string ""
this.setState((prevState) => {
// creates new immutable numbers object, using previous number values and the currently changed input value
const updatedNumbers = {
...prevState.numbers,
[name]: parsedValue
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names
};
// calculates the new total from updated numbers:
const newTotal = this.calculateTotal(updatedNumbers);
return {
numbers: updatedNumbers,
total: newTotal
}
})
}

render() {
return (
<div>
<input type="number" name="comp1" onChange={this.handleTotal} value={this.state.numbers.comp1} />
<input type="number" name="comp2" onChange={this.handleTotal} value={this.state.numbers.comp2}/>
<input type="number" name="comp3" onChange={this.handleTotal} value={this.state.numbers.comp3}/>
<input type="number" name="comp4" onChange={this.handleTotal} value={this.state.numbers.comp4}/>
<input type="number" name="comp5" onChange={this.handleTotal} value={this.state.numbers.comp5}/>
<input type="number" name="comp6" onChange={this.handleTotal} value={this.state.numbers.comp6}/>
<div id="total">{this.state.total}</div>
</div>
);
}
}

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

关于javascript - React - 循环输入并获取总和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60530892/

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