2
我有一個TodoList組件,它是App組件的子組件。我希望更改App組件的待辦事項列表的狀態。我試圖從TodoList組件傳遞toggleComplete功能到Todo組件,所以在onClick事件中,它會觸發並工作到App組件,以便更新狀態。反應:無法訪問父組件的功能,它作爲道具傳遞給子組件
我得到一個 「遺漏的類型錯誤:無法讀取屬性未定義 'toggleComplete'」 在TodoList.js
〜/ 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>
);
}
}
結合地圖的'這個'參數與綁定到'這'的道具得到它的工作。謝謝 :) –