繁体   English   中英

待办事项列表应用程序 - ReactJS 上的 onChange 不起作用?

[英]todo list app - onChange on ReactJS doesn't work?

我是 ReactJS 的新手,我正在用它做一个简单的列表。 我正在从事复选框的工作。 我想要做的是在我单击它时取消选中该框,反之亦然。 但是什么都没有改变,所以我想知道是否有什么问题......下面是 App.js 和 index.js 文件

import React from 'react';
import Todolist from './Todolist';
import todoData from './todoData';

class App extends React.Component {
    constructor(){
        super()
        this.state = {
            todos: todoData //grab the raw data 
        }
        this.handleChange = this.handleChange.bind(this)
    }

    handleChange (id){
        console.log(id)
        this.setState (prevState => {
            const updatedtodos = prevState.todos.map(todo => {
                if(todo.id == id) {
                    todo.completed = !todo.completed
                }
                return todo
            })
            return {
                todos: updatedtodos
            }
        })
    }

    render() {
        const TodoItem = this.state.todos.map(item => <Todolist key={item.id} item={item} handleChange={this.handleChange}/>)
        return(
            <div>
                {TodoItem}
            </div>

        );
    }
}
export default App;
import React from 'react';

function Todolist (props){

    return(
        <div className="wholelist">
        <input 
        type="checkbox" 
        checked={props.item.completed}
        onChange={()=> props.handleChange(props.item.id)}
        />
        <label className="items">{props.item.name}</label>
        </div>

    );
}

export default Todolist;

更改handleChange更改:

handleChange(id) {
  console.log(id);
  const updatedtodos = this.state.todos.map(todo => {
    if (todo.id === id) {
      todo.completed = !todo.completed;
    }
    return todo;
  });
  this.setState({
    todos: updatedtodos
  });
}

你需要改变两件事。

第一:

handleChange = (id) => { // I've changed this to an arrow function so it can access parent scope and you can use "this" keyword
    console.log(id)
    this.setState (prevState => {
        const todos = this.state.todos.map(todo => {
            if(todo.id === id) {
                todo.completed = !todo.completed
            }
            return todo
        })
        this.setState({ todos }) // you can use object shorthand here to change todos in state to use the todos set above 
    })
}

其次:

改变这个: handleChange={this.handleChange}

到: handleChange={() => this.handleChange(item.id)}

你说handleChange(id)需要带一个id,所以我们调用的时候需要传入一个

让我知道这是否有效!

暂无
暂无

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

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