繁体   English   中英

反应:无法访问作为道具传递给子组件的父组件的功能

[英]React: Unable to access the parent component's function which is passed as prop to child component

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

我在TodoList.js中收到“未捕获的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>
    );
  }
}

由于该错误来自父组件,因此您的问题似乎在该函数将其传递给子组件之前发生。 您的地图函数无权访问正确的函数 ,因此将其视为未定义的-请尝试以下操作:

{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/

上面的答案也可以使用箭头功能完成而无需绑定

{this.props.todos.map((todo, index) => {
  return <Todo todo={todo} toggleComplete={this.toggleComplete} id={index + 1} key={index+1}/>;
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM