問題:
それは奇妙です。子コンポーネントの入力ボックスに入力すると、「onChange」メソッドが更新を親コンポーネントに送信するはずです。最初に入力したものは更新に失敗しますが、次に入力したものはすべて更新されますが、現在の入力と同期していません。
私は Reactjs の初心者で、JavaScript の達人ではないので、何が起こっているのかわかりません。
例:
これは、「setState」が変更された後の状態と新しい状態を更新するためのオブジェクトのコンソール出力です。
初めて更新しようとしていvalue1
ます:
Object {value1: "5"}
Object {value1: "0", value2: "0", value3: "0", opening: "0"}
2回目の更新試行value1
:
Object {value1: "55"}
Object {value1: "5", value2: "0", value3: "0", opening: "0"}
ご覧のとおり、最初は何も更新されていません。その後、2回目は部分的に更新されました。
コード:
var Calculator =
React.createClass({
getInitialState:function(){
return {
inputValues:{
value1: "0",
value2: "0",
value3: "0",
opening: "0"
},
outputValues:{
buyRate: "0",
sellRate: "0",
buyStopLoss: "0",
buyTopProfit: "0",
sellStopLoss: "0",
sellTopProfit: "0"
}
}
},
//Not worrying about updating here yet. It' the child component below that is being funky.
update: function(update){
console.log("Calculator update was called");
this.setState(
update
);
},
render: function () {
return (
<div>
<div className="grid">
<div className="col fluid">
<h2>Input</h2>
<Input values={this.state.inputValues} onClick={this.handleClick} update={this.update} value1={this.state.value1} value2={this.state.value2} value3={this.state.value3} opening={this.state.opening}/>
</div>
<div className="col fluid">
<h2>Output</h2>
<Output />
</div>
</div>
</div>
);
}
});
var Input =
React.createClass({
getInitialState:function(){
return{
value1 : this.props.values.value1,
value2 : this.props.values.value2,
value3 : this.props.values.value3,
opening : this.props.values.opening
}
},
//Here is the update that is not updating the first time around.
update: function(key,value){
//console.log("Input Update was Called");
var newState = {};
newState[key]= value;
this.setState(newState);
//console.log(newState);
//console.log(this.state);
},
render:function(){
return (
<div>
<p><InputComponent update={this.update} name="value1" value={this.props.values.value1} /> / <InputComponent update={this.update} name="value2" value={this.props.values.value2}/> / <InputComponent update={this.update} name="value3" value={this.props.values.value3}/></p>
<p><InputComponent update={this.update} name="value3" value= {this.props.values.opening} /></p>
</div>
)
}
});
var InputComponent =
React.createClass({
handleChange: function(){
//console.log("handleChange was called");
var newValue = React.findDOMNode(this.refs.text).value.trim();
//console.log(this.props.name);
//console.log("newValue =");
//console.log(newValue);
this.props.update(this.props.name,newValue);
},
render: function() {
return <input type="text" ref="text" placeholder="Enter Value" onChange={this.handleChange} />;
}
});