反应 - 通过道具

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

目前,它给我一个错误,说“完整的”是不确定的。

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

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

建议在渲染todo component时,我得到的建议是通过app.js中的待办事项。

不确定该怎么做。有指针吗?

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;

将索引传递给
reactjs react-props
2个回答
2
投票
组件添加另一个道具:

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

确保组件与该索引支柱(即
toggleComplete

也是,您正在突变todo对象,而不是:

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

better做到这一点:

toggleComplete

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

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

我认为Max Kurtz的答案也是正确的,biging似乎是有问题的。在构造函数中绑定
Object.assign

函数,或使用箭头函数确保不会咬您。


您不将

Index
传递到
todo

,因此ToggleComplete不知道要更新哪个待办事项。 app.js

中的fix
通过索引作为道具:
const todos[index] = Object.assign({}, todo, {isCompleted: !isCompleted})
todo.js


0
投票
updatetogglecomplete直接调用道具:

this

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.