学习React,我正在构建一个简单的计算器。组件模型为:
- Calculator
- Sliders (input[ref=cars])
- Dashboard (p {this.state.cars})
Sliders
是具有一组输入的组件,应Dashboard
通过父级Calculator
状态将其传输到。
我的目标是使状态值Dashboard
随Sliders
输入组件的变化而变化。
var Calculator = React.createClass({
getInitialState: function() {
return {
cars: 0
};
},
render: function () {
return (
<div className="calculator">
<Sliders
cars={this.state.cars}
/>
<Dashboard
cars={this.state.cars}
/>
</div>
)
}
});
var Dashboard = React.createClass({
getInitialState:function () {
return {
cars: this.props.cars
}
},
render: function () {
return (
<div>
<h1>Dashboard</h1>
<p>Cars: {this.state.cars}</p>
</div>
)
}
})
var Sliders = React.createClass({
getInitialState: function() {
return {
cars: this.props.cars
};
},
handleInput: function () {
var state = {
cars: this.refs.cars.value
}
this.setState(state);
},
render: function () {
return (
<div className="sliders">
<input type="text" ref="cars" onChange={this.handleInput} value={this.state.cars}/>
</div>
)
}
})
正如我所了解的那样,它handleInput()
被触发了,所以状态为Sliders
置位。但是,它不会Calculator
作为“汽车” “转移”到父母的州。因此,Calculator
状态未更新=>Dashboard
状态也未更新。
如何在滑块和仪表盘之间共享计算器的父状态?
我知道,SO上有很多类似的问题,但是很难找到具体的有用案例,尤其是当您在React中完成菜鸟的时候。因此,很抱歉重复。
组件不共享状态。但是,一个组件的状态可以成为另一组件的道具。
在你的情况,cars
应该是国家Calculator,
和Slide
和Dashboard
应只检索cars
当道具。如果输入发生更改,Sliders
则应通知Calculator
更改,以便它可以更新其状态并重新呈现(这也会导致Sliders
和Calculator
更新):
var Calculator = React.createClass({
getInitialState: function() {
return {
cars: 0
};
},
onUpdate: function (cars) {
this.setState({cars});
},
render: function () {
return (
<div className="calculator">
<Sliders
cars={this.state.cars}
onUpdate={this.onUpdate}
/>
<Dashboard
cars={this.state.cars}
/>
</div>
)
}
});
var Dashboard = React.createClass({
render: function () {
return (
<div>
<h1>Dashboard</h1>
<p>Cars: {this.props.cars}</p>
</div>
)
}
})
var Sliders = React.createClass({
handleInput: function (event) {
this.props.onUpdate(event.target.value);
},
render: function () {
return (
<div className="sliders">
<input type="text" ref="cars" onChange={this.handleInput} value={this.props.cars}/>
</div>
)
}
})
尽可能少的组件应具有状态,并且状态在树中应尽可能高。另请参见getInitialState中的道具是反模式
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句