反应-传递道具

时间:2018-11-24 23:44:18

标签: reactjs react-props

当前,它给我一个错误,提示isCompleted未定义。

todo.isCompleted = todo.isCompleted吗? false:true;

上面的代码是引发错误的原因。

我得到的建议是,在渲染Todo组件时在App.js中传递todoIndex道具。

不确定如何执行此操作。有指针吗?

import React, { Component } from 'react';
import './App.css';
import ToDo from './components/ToDo.js';

class App extends Component {
 constructor(props) {
   super(props);
    this.state = {
     todos: [
       { description: 'Walk the cat', isCompleted: true },
       { description: 'Throw the dishes away', isCompleted: false },
       { description: 'Buy new dishes', isCompleted: false }],
     newTodoDescription: ''
  };
}

deleteToDo(deleteToDo) {
  console.log(this);
  let newToDos = this.state.todos.filter((todo) => {
    return todo !== deleteToDo
  } )
  this.setState({ todos: newToDos });
}

handleChange(e) {
 this.setState({ newTodoDescription: e.target.value })
}

handleSubmit(e) {
  e.preventDefault();
  if (!this.state.newTodoDescription) { return }
  const newTodo = { description: this.state.newTodoDescription, isCompleted: false };
  this.setState({ todos: [...this.state.todos, newTodo], newTodoDescription: '' });
}

toggleComplete(index) {
  const todos = this.state.todos.slice();
  const todo = todos[index];
  todo.isCompleted = todo.isCompleted ? false : true;
  this.setState({ todos: todos });
}


render() {
 return (
  <div className="App">
    <ul>
    { this.state.todos.map( (todo, index) =>
      <ToDo key={ index } description={ todo.description } isCompleted={ todo.isCompleted } toggleComplete={ this.toggleComplete.bind(this) } deleteToDo={() => this.deleteToDo(todo)} />

    )}
    </ul>
    <form onSubmit={ (e) => this.handleSubmit(e) }>
     <input type="text" value={ this.state.newTodoDescription } onChange={ (e) => this.handleChange(e) } />
     <input type="submit" />
   </form>
  </div>
);
}
}

export default App;

ToDo.js

import React, { Component } from 'react';

class ToDo extends Component {

  toggleComplete = () => {
    this.props.toggleComplete(this.props.todoIndex)
  }

  render() {

    return (

    <ul>
     <input type= "checkbox" checked= { this.props.isCompleted } 
    onChange= { this.handleToggleClick.bind(this)} />
     <span>{ this.props.description }</span>
     <button onClick={ this.props.deleteToDo }> X </button>
  </ul>

  );
 }
}
export default ToDo;

1 个答案:

答案 0 :(得分:2)

要将索引传递到ToDo组件,请添加另一个道具:

<ToDo key={index} todoIndex={index} ... />

并确保组件使用该索引道具(即

)调用toggleComplete
class ToDo extends React.Component {
  toggleComplete() {
    this.props.toggleComplete(this.props.todoIndex)
  }
}

此外,您正在toggleComplete函数中更改todo对象,而不是:

todo.isCompleted = todo.isCompleted ? false : true;

最好这样做:

const todos[index] = {...todo, isCompleted: !todo.isCompleted }

或使用Object.assign

const todos[index] = Object.assign({}, todo, {isCompleted: !isCompleted})

我认为Max Kurtz的答案也是正确的,this绑定似乎有问题。将toggleComplete函数绑定到构造函数中,或使用箭头函数确保this不咬你。