专家!
我对React有问题。我正在尝试通过回调从子级呈现父级。假设addTask函数将调用父组件的渲染。但这不起作用,我也不知道为什么。
这是代码。任何帮助将不胜感激。
var tasks = [
{ type : "Personal",
task_list : [
"Visit laundty",
"Mend bike",
"Call mom"]
}];
var AddTask = React.createClass({
getInitialState : function() {
return {
add: false
};
},
addTask: function(e) {
e.preventDefault();
var task = document.getElementById('taskText').value;
var arr = tasks[0].task_list.push(task);
console.log(tasks[0].task_list);
this.setState({add: true});
this.props.callback;
},
render: function() {
return (
<div
className='user_task'>
<textarea
className = 'usr_task_text' id='taskText' >
</textarea>
<button
type = 'button'
className='btn btn-primary usr_new_action_btn'
onClick = {this.addTask}> Done
</button>
</div>
)
}});
var Tasks = React.createClass({
render: function() {
var lists = this.props.ddata.map(function(item, index) {
return (
<li key={index}
className='user_task'>
{item}
</li>
)
})
return <ul> {lists} </ul> ;
}
});
var App = React.createClass({
getInitialState : function() {
return {
update: 1
};
},
update: function(e) {
console.log("updated!");
},
render: function() {
var chpt;
var key_ = 0;
var p_ = new Array();
if (tasks.length > 0) {
var chpt = tasks.map(function(item, index) {
return (
<div key = {index}>
<div
className = "user_header">
<span className="user_header_span" >
{item.type}
</span>
</div >
<AddTask callBack = {i => this.update}/>
<Tasks ddata = {item.task_list} />
</div>
)
})
} else {
chpt = <p></p>
}
return (
<div className="row">
<div className = "jumbotron col-md-3 user_act">
{chpt}
</div>
</div>
);
}
});
ReactDOM.render(
<App />,
document.getElementById('main_')
最佳答案
您正在引用this.props.callback
,但未调用它。添加括号以调用该函数:
this.props.callback();