我正在尝试通过在输入字段(num1 = 2,num2 = 2)中采用默认值来添加两个数字。没有添加按钮,如何将这两个数字相加。例如,例如,如果用户将num1的值从2更改为4,则它应更新添加2号值的值(num1 = 4 + num2 = 2 =结果6)。它应该自动更新第三个输入字段值或其中包含结果值的文本。
import React from "react";
import ReactDOM from "react-dom";
class Test extends React.Component {
constructor(props) {
super(props);
this.state = {
result: 0,
num1: 2,
num2: 2
};
this.handlenum1Change = this.handlenum1Change.bind(this);
this.handlenum2Change = this.handlenum2Change.bind(this);
}
handlenum1Change(evt) {
console.log(evt.target.value);
this.setState({ num1: Number(evt.target.value) });
}
handlenum2Change(evt) {
console.log(typeof evt.target.value);
this.setState({ num2: Number(evt.target.value) });
}
addAction = event => {
let x = this.state.num1 + this.state.num2;
this.setState({ result: x });
};
render() {
return (
<form>
<label>
<input
type="number"
name="num1"
value={this.state.num1}
onChange={this.handlenum1Change}
/>
<input
type="number"
name="num2"
value={this.state.num2}
onChange={this.handlenum2Change}
/>
<input type="button" onClick={this.addAction} value="Add" />
<input type="text" value={this.state.result} readOnly />
</label>
</form>
);
}
}
export default Test;
答案 0 :(得分:1)
您可以添加更改后的值和未更改的值,并在更新其中一个数字时将其设置为新的result
。
示例
class Test extends React.Component {
state = {
result: 4,
num1: 2,
num2: 2
};
handlenum1Change = evt => {
const num1 = Number(evt.target.value);
this.setState(prevState => ({
num1,
result: num1 + prevState.num2
}));
};
handlenum2Change = evt => {
const num2 = Number(evt.target.value);
this.setState(prevState => ({
num2,
result: prevState.num1 + num2
}));
};
render() {
return (
<form>
<label>
<input
type="number"
name="num1"
value={this.state.num1}
onChange={this.handlenum1Change}
/>
<input
type="number"
name="num2"
value={this.state.num2}
onChange={this.handlenum2Change}
/>
<input type="text" value={this.state.result} readOnly />
</label>
</form>
);
}
}
ReactDOM.render(<Test />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>