Javascript 带参数的回调函数 ReactJS
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45359113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Callback Function With Parameters ReactJS
提问by ChaseHardin
Working with ReactJS and having trouble understanding how callback functionswork with ReactJS.
使用 ReactJS 并且无法理解如何callback functions使用 ReactJS。
I have a parent component titled TodoFormComponent, which initializes my list of todo items. I've created a callback function on the TodoItemsComonent, but it doesn't trigger the updateItemmethod and display the selecteditem.
我有一个名为 的父组件TodoFormComponent,它初始化我的待办事项列表。我在 上创建了一个回调函数TodoItemsComonent,但它不会触发该updateItem方法并显示该selected项目。
Question:How can I pass data from the child to the parent? I want to pass the selected todo item to the parent so that I can update the master todo list.
问题:如何将数据从孩子传递给父母?我想将选定的待办事项传递给父项,以便我可以更新主待办事项列表。
Parent Component (TodoFormComponent)
父组件(TodoFormComponent)
The TodoFormComponenthas selectedTask, which should be triggering the updateItemmethod.
的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)
The TodoItemsComponenthas an onClickto update the selected value. This gets updated in the selectedTaskfunction.
import * as React from "react";
的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>
)
}
}
回答by Prakash Sharma
Whenever you want to pass data from child to parent you pass a function as a prop to child and from child you call that function using this.props.passedFunction(yourDataToPassToParent)
每当您想将数据从子级传递给父级时,您将一个函数作为道具传递给子级,并从子级中调用该函数 this.props.passedFunction(yourDataToPassToParent)
Here from your parent component you are passing the selectedTaskfunction as prop, so you should call this.prop.selectedTask()with the data to be passed to parent like:
从您的父组件中,您将selectedTask函数作为道具传递,因此您应该this.prop.selectedTask()使用要传递给父组件的数据进行调用,例如:
<button
type="button"
className="btn btn-xs btn-danger"
onClick={() => {this.props.selectedTask(item)}}
>
X
</button>
Also the way you are passing the selectedTaskin your parent is wrong. You should pass it like this:
此外,您传递selectedTask给父母的方式是错误的。你应该像这样传递它:
<TodoItemsComponent items={this.state.todoItems} selectedTask={this.updateItem}/>
回答by error404
In your TodoItemsComponent,updateItem() is passed as prop. So you need to call the this.props.updateItem()in your onClick method.
在您的 TodoItemsComponent 中,updateItem() 作为道具传递。所以你需要this.props.updateItem()在你的 onClick 方法中调用。
So your button should be:
所以你的按钮应该是:
<button
type="button"
className="btn btn-xs btn-danger"
onClick={() =>
{this.props.selectedTask(item)}}>X
</button>
and Update your parent components UpdateItem method to receive properties as item. Like this:
并更新您的父组件 UpdateItem 方法以将属性作为项目接收。像这样:
updateItem (e) {
console.log('Selected Value:: ', e);
}
And to pass method in children you need to
要在孩子中传递方法,您需要
<TodoItemsComponent items=
{this.state.todoItems} selectedTask={this.updateItem}/>
If you do this: {()=>this.updateItem()}then it will initialize the method. So you need just pass the function reference.
如果您这样做:{()=>this.updateItem()}那么它将初始化该方法。所以你只需要传递函数引用。
回答by marzelin
fixed code:
固定代码:
class TodoItemsComponent extends React.Component {
constructor(props) {
super(props);
}
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.props.selectedTask(item);
}}
>
X
</button>
</div>
</li>
);
})}
</ul>
);
}
}
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(item) {
this.setState({ selected: item });
}
render() {
return (
<div className="row">
<div className="container">
<div className="well col-xs-6 col-xs-offset-3">
<h1>To do: </h1>
<h3>
Selected task: {JSON.stringify(this.state.selected)}
</h3>
<div name="todo-items">
<TodoItemsComponent
items={this.state.todoItems}
selectedTask={this.updateItem}
/>
</div>
<div name="add-todo-item" />
</div>
</div>
</div>
);
}
}
const App = () => <TodoFormComponent />;
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
playground: https://codesandbox.io/s/LgrGKK9og
回答by pethel
You have to send updateItem as a prop to the child Component.
您必须将 updateItem 作为道具发送给子组件。
const Parent = () =>
<div>
<TodoItemsComponent items={this.state.todoItems} selectedTask={updateItem}/>
</div>
Also update
也更新
updateItem (item) {
this.setState({ selected: item })
console.log( 'Selected Value:: ', item);
}
回答by Kamil Socha
Some pseudo-code:
一些伪代码:
class Parent extends React.Component {
render() {
return (<Child id={1} onClick={(id) => console.log(id)}/>);
}
}
class Child extends React.Component {
render() {
return (<div onClick={() => this.props.onClick(this.props.id)}></div>);
}
}
Console.log will output "1"
Console.log 将输出“1”
More: link
更多:链接

