首页 > 解决方案 > 我试图弄清楚如何在反应中使按钮切换,但我没有弹出任何错误。这是怎么回事?

问题描述

查看一个简单的待办事项应用程序,但切换按钮没有处理在单击按钮处理程序后标记待办事项完成的样式。我没有收到任何错误,但可能忽略了一些简单的事情。

import React from 'react';
import './App.css';
import Header from "./components/Header";
import Addtodo from "./components/Addtodo";
import Todos from "./components/Todos";
import {Provider} from "./context"

function App() {
  return (
    <Provider>
    <div className="app-container">
      <Header></Header>
      <Addtodo></Addtodo>
      <Todos></Todos>
    </div>
    </Provider>
  );
}

export default App;

这是组件。

import React, { Component } from 'react'

export default class Addtodo extends Component {
    render() {
        return (
            <form>
                <input type="text" className="form-control rounded-0" placeholder="Write down a task"/>

            <button className="form-control rounded-0 btn-secondary" type="submit">Add a task</button>
            </form>
        )
    }
}

import React from 'react'

export default function Header() {
    return (
        <div className="card bg-info text-center text-light rounded-0">
            <h1 className="display-4">
                <i className="fas fa-clipboard-list mr-3"></i> <span className="text-dark mr-3">MERN</span> Task Master!
            </h1>
        </div>
    )
}

import React, { Component } from 'react'
import { Consumer } from "../context"

export default class Todo extends Component {
    style = () => {
    const { complete } = this.props.todo
    return { textDecoration: complete ? "line-through" : "none" }
    }
    toggle = (id, dispatch) => {
        dispatch({ type: "TOGGLE", payload: id })
    }
    render() {
        const { title, id } = this.props.todo
        return (
            <Consumer>{value =>{
            const { dispatch } = value
            return <h3 className="text-dark text-center p-1 bg-light border-bottom" style=
            {this.style()}>
                <i className="far fa-times-circle fa-sm float-left m-1 text-danger"></i>{title}
                <input type="checkbox" className="m-2 float-right" onChange={this.toggle.bind(this,
                    id, dispatch)} />
            </h3>
             }}</Consumer>

        )
    }
}

import Todo from "./Todo";
import React, { Component } from 'react'
import {Consumer} from "../context"

//import consumer which holds the value of the state
//for each todo we are just returning one by passing props
export default class Todos extends Component {
    render() {
        return (
            <Consumer>{value =>{
                const {todos} = value
                return todos.map(t=><Todo todo={t} key={t.id}></Todo>)
            }}</Consumer>
        )
    }
}

有没有人可以解决为什么这不起作用?我有点挣扎。如果可能的话,一个例子应该会有所帮助。

标签: reactjs

解决方案


所以对于初学者来说,你不用按钮做任何事情。您没有处理任何组件中的点击。

其次,您没有使用“连接”功能连接来自商店的数据。

老实说,您似乎遗漏了很多东西,但您可以在此处的 React Redux 网站上查看如何使用 React Redux 创建待办事项应用程序的示例。

希望这可以帮助。


推荐阅读