我正在尝试创建一个待办事项列表,在完成一项任务后, 只有这样才能启用下一个任务(勾选完成)。
这是我到目前为止所做的:
/** @jsx React.DOM */
$(function(){
var tasks = [
{title: "Wake up"},
{title: "Eat dinner"},
{title: "Go to sleep"}
];
var Task = React.createClass({
getInitialState: function(){
return {locked:true, done:false}
},
handleClick: function(e){
this.setState({done: !this.state.done});
var selector = '.toggle[data-order="'+(this.props.order+1)+'"]';
this.setState({locked: true})
console.log(selector)
console.log($(selector).removeAttr("disabled"))
},
render: function() {
var locked;
//Fix first task to not be disabled
if(this.props.order == 0 && this.state.done === false)
locked = false;
else
locked = this.state.locked;
var done = this.state.done ? "Done":"Not done";
var classView = "task" + (this.state.done ? " done":" not-done");
return (
<div class="todo well well-sm" class={classView}>
<span class="description">{this.props.title}</span>
<button type="button" onClick={this.handleClick} data-order={this.props.order} disabled={locked} class="toggle btn btn-default btn-xs pull-right">
<span class="glyphicon glyphicon-unchecked"></span> Done
</button>
</div>
);
}
});
var TaskList = React.createClass({
render: function(){
var i = -1;
var taskNodes = this.props.data.map(function (task) {
return <Task title={task.title} order={++i} />;
});
return (
<div class="task-list">
{taskNodes}
</div>
);
}
});
var Guider = React.createClass({
render: function(){
return (
<div>
<TaskList data={this.props.data} />
</div>
);
}
});
React.renderComponent(<Guider data={tasks} />, document.body);
});
下一个按钮,仍然没有被禁用,我觉得我一般都做错了(不是根据反应“禅”)。
顺便说一下: 如何在没有用户触发的情况下更改dom元素的状态?我应该使用任何ID?
答案 0 :(得分:7)
如果将数据启动到非根组件,则很难更新其他组件。所以我更喜欢将数据保存到根组件中,然后将点击处理程序作为props传递。现在,您将可以访问非根组件中的该处理程序。调用它将更新根组件,以及其他非根组件。
这是有效的jsFiddle - http://jsfiddle.net/ammit/wBYHY/5/
var Task = React.createClass({
handleClick: function (e) {
// Passing order of task
this.props.clicked(order);
},
render: function () {
return ( <button type="button" onClick={this.handleClick}></button> );
}
});
var TaskList = React.createClass({
getInitialState: function(){
// initiate tasks here
},
whenClicked: function(order){
// Revise the tasks using `order`
// Finally do a setState( revised_tasks );
},
render: function(){
return ( <Task clicked={this.whenClicked} /> );
}
});