我有一个我想从postal.js订阅中取消选中的组件。使用我的代码下面的复选框总是被选中。
我将值存储在state中并在ComponentDidMount中设置它。我收到订阅后可以告诉我如何取消选中它:
更新:
var SelectAll = React.createClass({
getInitialState: function() {
return {
checked:false
};
},
handler: function(e) {
var updatedContacts = [],
contacts = this.props.data.contacts,
topic = 'selectAll',
checked = false,
channel = 'contact';
contactChannel.publish({
channel: channel,
topic: topic,
data: {
selectAll: this.state.checked
}});
this.setState({checked: event.target.value});
},
render: function() {
return (
<div className="contact-selector">
<input type="checkbox" checked={this.state.checked}
onChange={this.handler} ref="checkAll" />
</div>
);
},
setUnChecked: function(){
this.setState({ selected: false });
},
componentDidMount: function() {
var self = this;
contactChannel.subscribe("deselectedContact", function(data) {
self.setUnChecked();
});
}
});
module.exports = SelectAll;
答案 0 :(得分:1)
这样的事可能吗?
setChecked: function(isChecked) {
this.setState({
selected: isChecked
});
},
componentDidMount: function() {
var self = this; // <--- storing the reference to "this" so that it can be later used inside nested functions
contactChannel.subscribe("deselectedContact", function(data) {
self.setChecked(false); // <--- "this" would not refer to the react component hence you have to use self
});
}
答案 1 :(得分:1)
如果您在ReactJS中为表单字段指定checked
属性,则将其设置为controlled。这意味着,用户简单按下它不会改变它的状态(或者在文本字段的情况下写入不会改变文本)。您需要自己设置,例如在handler()
函数中。
P.S。组件内部的数据流有点混乱 - 根据我刚刚写的内容,你应该在this.state.XXX
属性中使用一些checked={XXX}
变量,当按下ckbx时,更新它在handler()
函数中使用`this.setState()'。这将触发DOM中组件的自动重新呈现(当然,如果状态发生变化)。
修改
<script src="https://fb.me/JSXTransformer-0.13.3.js"></script>
<script src="https://fb.me/react-0.13.3.js"></script>
<div id="container">
</div>
<script type="text/jsx;harmony=true">void function() {
'use strict';
var MyComponent = React.createClass({
getInitialState: function() {
return {
checked: false
};
},
handle: function(e) {
/*
Do your processing here, you might even prevent the checkbox from changing state - actually that is the main purpose of Facebook implementing the controlled/uncontrolled elements thing - to have full control of the input.
*/
var currentMinute = Math.floor(new Date().getTime() / 1000 / 60);
//The checkbox can be changed only in odd minutes
if(currentMinute % 2 == 1) {
this.setState({checked: e.target.checked});
}
},
render: function() {
return <input type="checkbox" checked={this.state.checked} onChange={this.handle} />;
}
});
React.render(<MyComponent />, document.getElementById('container'));
}()</script>
答案 2 :(得分:0)
您可以使用componentWillReceiveProps()
,在安装的组件接收新道具之前调用它。如果您需要更新状态以响应prop更改(例如,重置它),您可以比较this.props
和nextProps
并使用此方法中的this.setState()
执行状态转换。 / p>