使用ReactJS并且无法理解_2552728如何与ReactJS一起使用 .
我有一个 Headers 为 TodoFormComponent
的父组件,它初始化我的待办事项列表 . 我在 TodoItemsComonent
上创建了一个回调函数,但它没有触发 updateItem
方法并显示 selected
项 .
问题:如何将数据从孩子传递给父母?我想将选定的待办事项传递给父项,以便我可以更新主待办事项列表 .
Parent Component (TodoFormComponent)
TodoFormComponent
有 selectedTask
,它应该触发 updateItem
方法 .
import * as React from "react";
import TodoItemsComponent from "../todo-items/todo-items.component";
import AddTodoItemComponent from "../add-todo-item/add-todo-item.component";
export default class TodoFormComponent extends React.Component {
constructor(){
super();
this.state = {
todoItems: [
{ id: '1', todo: 'First Todo Item' },
{ id: '2', todo: 'Second Todo Item' },
{ id: '3', todo: 'Third Todo Item' }
],
selected: {}
};
this.updateItem = this.updateItem.bind(this);
}
updateItem () {
console.log('Selected Value:: ', this.state.selected);
}
render() {
return (
<div className="row">
<div className="container">
<div className="well col-xs-6 col-xs-offset-3">
<h1>To do: </h1>
<div name="todo-items">
<TodoItemsComponent items={this.state.todoItems} selectedTask={() => {this.updateItem}}/>
</div>
<div name="add-todo-item">
<AddTodoItemComponent/>
</div>
</div>
</div>
</div>
)
}
}
Child Component (TodoItemsComponent)
TodoItemsComponent
有 onClick
来更新所选值 . 这会在 selectedTask
函数中更新 . import * as React from "react";
export default class TodoItemsComponent extends React.Component {
constructor(props) {
super(props);
}
selectedTask (item) {
this.setState({selected: item})
}
render() {
return (
<ul className="list-group">
{
this.props.items.map((item) => {
return (
<li className="list-group-item">
{item.todo}
<div className="pull-right">
<button
type="button"
className="btn btn-xs btn-success">
✓
</button> <button
type="button"
className="btn btn-xs btn-danger"
onClick={() => {this.selectedTask(item)}}
>X
</button>
</div>
</li>
)
})
}
</ul>
)
}
}
5 回答
每当你想要将数据从子节点传递给父节点时,你将一个函数作为prop传递给子节点,并从子节点传递给你的函数使用
this.props.passedFunction(yourDataToPassToParent)
在您的父组件中,您将
selectedTask
函数作为prop传递,因此您应该调用this.prop.selectedTask()
,并将数据传递给父类,如:你在父母中传递
selectedTask
的方式也是错误的 . 你应该像这样传递它:在您的TodoItemsComponent中,updateItem()作为prop传递 . 因此,您需要在onClick方法中调用
this.props.updateItem()
.所以你的按钮应该是:
并更新您的父组件UpdateItem方法以接收属性作为项目 . 像这样:
并且需要通过孩子的方法
如果你这样做:
{()=>this.updateItem()}
然后它将初始化方法 . 所以你需要传递函数参考 .您必须将updateItem作为prop发送到子Component .
还要更新
一些伪代码:
Console.log将输出“1”
更多:link
固定代码:
游乐场:https://codesandbox.io/s/LgrGKK9og