[英]React Updating Same State with Different Components
In my App I have an update
function. 在我的应用程序中,我具有
update
功能。
update: function() {
this.setState({
red:this.refs.red1.refs.range.getDOMNode().value
green:this.refs.green1.refs.range.getDOMNode().value,
blue:this.refs.blue1.refs.range.getDOMNode().value
})
},
I want to add a red2 ref and update the red state. 我想添加一个red2 ref并更新红色状态。 How do I do this?
我该怎么做呢? Adding another
red:
would just overwrite the first one. 添加另一个
red:
只会覆盖第一个red:
。
Edit:
I tried adding an update2
function. 我尝试添加一个
update2
函数。 Which updates the state as expected. 它将按预期更新状态。 I only have one issue with the code.
我的代码只有一个问题。 When I change
red2
to some number, red1
doesn't change. 当我将
red2
更改为某个数字时, red1
不会更改。 It's value should be the state. 它的价值应该是国家。 I guess since I'm not calling
red1
's update
function its value doesn't get updated to match the current state. 我猜因为我没有调用
red1
的update
函数,所以它的值不会被更新以匹配当前状态。
update2: function() {
this.setState({
red: this.refs.red2.refs.range.getDOMNode().value,
green: this.refs.green2.refs.range.getDOMNode().value,
blue: this.refs.blue2.refs.range.getDOMNode().value,
})
},
XML representation: XML表示形式:
<ColorPicker ref="red1" min={0} max={255} step={1} val={this.state.red} update={this.update} />
<ColorPicker ref="red2" min={0} max={255} step={1} val={this.state.red} update={this.update2} type="number" />
How do I get red1
and red2
to update the state and have the state reflected as their value whenever one of the two components changes. 每当两个组件之一发生更改时,如何获取
red1
和red2
更新状态并将状态反映为它们的值。
Edit 2:
Color picker component: 拾色器组件:
var ColorPicker = React.createClass({
propTypes: {
min: React.PropTypes.number,
max: React.PropTypes.number,
step: React.PropTypes.number,
val: React.PropTypes.number,
label: React.PropTypes.string,
update: React.PropTypes.func.isRequired,
type: React.PropTypes.oneOf(['number', 'range']),
},
getDefaultProps: function() {
return {
min: null,
max: null,
val: 0,
step: 1,
label: '',
type: 'range',
}
},
render: function() {
return (
<div>
<input
ref="range"
type={this.props.type}
min={this.props.min}
max={this.props.max}
step={this.props.step}
defaultValue={this.props.val}
onChange={this.props.update}
/>
</div>
)
}
})
You are only setting the defaultValue so when second colorPicker changes the value of red, firstColorPicker is not updated: 您仅设置defaultValue,所以当第二个colorPicker更改红色的值时,firstColorPicker不会更新:
Instead of using 而不是使用
defaultValue ={this.props.val}
use 采用
value={this.props.val}
Here is a working fiddle: http://jsfiddle.net/r7ktbmwo/ 这是一个有效的小提琴: http : //jsfiddle.net/r7ktbmwo/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.