React:无法访问父组件的函数,该函数作为prop传递给子组件

问题描述 投票:2回答:2

我有一个TodoList组件,它是App组件的子组件。我希望更改App组件的待办事项列表的状态。我试图将TodoList组件中的toggleComplete函数传递给Todo组件,因此在onClick事件中它会触发并向上运行到App组件,以便我可以更新状态。

我在TodoList.js中得到一个“Uncaught TypeError:无法读取未定义的属性'toggleComplete'”

〜/ SRC /组件/ Todo.js

import React, {PropTypes} from 'react';

export default class Todo extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <li className={this.props.todo.done ? 'completed' : 'view'}>
        <div className="view">
          <input onClick={this.props.toggleComplete(this.props.id)} className="toggle" type="checkbox" checked={this.props.todo.done} />
          <label>{this.props.id}: {this.props.todo.title}</label>
          <button className="destroy"></button>
        </div>
      </li>
    );
  }
}

〜/ SRC /组件/ TodoList.js

import React, {PropTypes} from 'react';
import Todo from './Todo'

export default class TodoList extends React.Component {
  constructor(props) {
    super(props);
  }
  toggleComplete(todoID){
    console.log('hit toggleComplete TodoList');
  }

  render() {
    return (
      <section className="main">
        <ul className="todo-list">
          {this.props.todos.map(function(todo, index){
            return <Todo todo={todo} toggleComplete={this.toggleComplete} id={index + 1} key={index+1}/>;
          })}
        </ul>
      </section>
    );
  }
}

〜/ SRC / App.js

import React, { Component } from 'react';
import Header from './component/Header'
import TodoList from './component/TodoList'
import TodoFooter from './component/TodoFooter'
import Footer from './component/Footer'

export default class App extends Component {
  constructor(){
    super();
    this.state = {
      todos: [
        {title: 'Taste JavaScript', done: true},
        {title: 'Buy Unicorn', done: false},
        {title: 'eat all day', done: false},
        {title: 'sleep all night', done: true}
      ]
    }
  }

  render() {
    return (
      <div>
        <section className="todoapp">
          <Header />
          <TodoList todos={this.state.todos} />
          <TodoFooter />
        </section>
        <Footer />
      </div>
    );
  }
}
reactjs
2个回答
3
投票

您的问题似乎在函数进入子组件之前发生,因为错误来自您的父组件。您的map function无法访问正确的内容,因此将其视为未定义 - 请尝试以下方法:

{this.props.todos.map(function(todo, index){
  return <Todo todo={todo} toggleComplete={this.toggleComplete} id={index + 1} key={index+1}/>;
}, this)} // use the optional "this" argument to the map function

这里有一个小提琴,展示一个简单的父母渲染他们的孩子与父母的范围相同的例子:https://jsfiddle.net/v5wd6Lrg/1/


0
投票

上述答案也可以使用箭头功能完成,无需绑定

{this.props.todos.map((todo, index) => {
  return <Todo todo={todo} toggleComplete={this.toggleComplete} id={index + 1} key={index+1}/>;
});
© www.soinside.com 2019 - 2024. All rights reserved.