2 回答

TA贡献1827条经验 获得超8个赞
value传递给的updateCodeX不是它自己的值,而是event内部的值event.target.value,并添加+以将状态值转换为数字:
class Test extends React.Component {
state = {
code1: 40,
code2: 40,
code3: 40,
total : 0
}
updateCode1 = e => {
this.setState({
code1: e.target.value
},
() => {
this.updateTotal();
});
}
updateCode2 = e => {
this.setState({
code2: e.target.value
},
() => {
this.updateTotal();
});
}
updateCode3 = e => {
this.setState({
code3: e.target.value
},
() => {
this.updateTotal();
});
}
updateTotal = () => {
this.setState(prevState => ({
total: (+prevState.code1 + +prevState.code2 + +prevState.code3),
}),
() => {
if (this.state.total !== 100) {
this.setState({
isTotalInvalid: true
});
} else {
this.setState({
isTotalInvalid: false
});
}
});
}
render() {
return (
<div>
<input type="number" defaultValue="40" min="0" max="100" onKeyPress={this.handleInput} onBlur={this.updateCode1} />
<input type="number" defaultValue="40" min="0" max="100" onKeyPress={this.handleInput} onBlur={this.updateCode2} />
<input type="number" defaultValue="40" min="0" max="100" onKeyPress={this.handleInput} onBlur={this.updateCode3} />
Total Field:
<span fontSize={14} weight={700}>{this.state.total}</span>
</div>);
}
}
ReactDOM.render( < Test / > , document.querySelector('#test'));
<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="test"></div>

TA贡献1798条经验 获得超7个赞
您可以使用一个处理程序一次性完成,如下所示:一个工作的plnkr
handleInput = (e) => {
const key = e.target.name;
if (!key) { return; }
const value = e.target.value ? parseFloat(e.target.value) : 0;
const oldValue = this.state[key] ? this.state[key] : 0;
const total = (this.state.total - this.state[key]) + value;
console.log('key: ', key, ' value: ', value, ' total: ', total);
this.setState({ [key]: value, total })
}
添加回答
举报