感谢您访问我的问题。 我正在通过react做一个简单的计算器。
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.2/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.6.2/react-dom.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Task 4</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.38/browser.js"></script>
</head>
<body>
<div id="calculator"/>
<script type="text/babel">
var Calculate=React.createClass({
getInitialState:function(){
return{
firstvalue: 0, secondvalue: 0, operation : "+", answer: 0
}
},
handleFirstValueChange(event)
{
var localvalue=event.target.value.replace(/\s+/g, ' ').trim()
this.setState({
firstvalue:localvalue
});
this.Answer()
},
handleSecondValueChange(event)
{
var localvalue=event.target.value.replace(/\s+/g, ' ').trim()
this.setState({
secondvalue:localvalue
})
this.Answer()
},
handleSum(event)
{
this.setState({
operation:"+",
})
this.Answer()
},
handleSub(event)
{
this.setState({
operation:"-"
})
this.Answer()
},
handleMul(event)
{
this.setState({
operation:"*"
})
this.Answer()
},
handleDiv(event)
{
this.setState({
operation:"/"
})
this.Answer()
},
Answer()
{
switch(this.state.operation)
{
case "+" :
this.setState({
answer:Number(this.state.firstvalue)+Number(this.state.secondvalue)
})
break;
case "-" :
this.setState({
answer:Number(this.state.firstvalue)-Number(this.state.secondvalue)
})
break;
case "*" :
this.setState({
answer:Number(this.state.firstvalue)*Number(this.state.secondvalue)
})
break;
case "/":
this.setState({
answer:Number(this.state.firstvalue)/Number(this.state.secondvalue)
})
break;
}
},
render:function(){
return(
<div>
<input type="text" className="search-field" onChange={this.handleFirstValueChange}/>
<input type="text" className="search-field" onChange={this.handleSecondValueChange}/>
<div/>
<button onClick={this.handleSum}>
Сложить
</button>
<button onClick={this.handleSub}>
Вычесть
</button>
<button onClick={this.handleMul}>
Умножить
</button>
<button onClick={this.handleDiv}>
Поделить
</button>
<div>{this.state.firstvalue} {this.state.operation} {this.state.secondvalue} ={this.state.answer} </div>
</div>
)}
});
ReactDOM.render(
<Calculate/>,
document.getElementById("calculator")
);
</script>
</body>
</html>
我想在编辑第一个或第二个字段时提供答案。但是它仅在再次按下按钮或编辑字段后才呈现。我没有看到如何解决,我认为可以通过render来解决,但是在这两个字段上我被称为Answer()函数,但它没有给我结果。我正在尝试将Answer()与render中的事件链接,但未成功。 非常感谢。 前2个scr是stackoverflow。 我想要这个结果。编辑字段或按钮,然后立即给出答案。
答案 0 :(得分:0)
this.state不会在调用this.setState()时发生突变-您可以将渲染中的答案作为普通变量来计算,也可以使用this.Answer(localvalue)代替从this.state中读取以前的状态-大约30分钟前 非常感谢。 我加 const Answer = this.Answer(); 在渲染中