如何在我的 React JS 应用程序中创建交互式复选框?

How can I create interactive checkboxes in my React JS app?

描述

我对 React JS 很陌生,这可能会显示在我的代码中。我正在尝试制作一个简单的待办事项应用程序,它将帮助我了解如何使用 React 进行编码。如果复选框被选中,应用程序应该只显示“完成”,否则显示“未完成”。但是,复选框不会在点击时更新。

我认为问题在于不理解 React 逻辑,导致使用默认变量(例如:checked == true)反复调用 Checkbox() 函数。

如有任何建议,我们将不胜感激!

代码和示例

以截图为例:

文件树(不包括node_modules文件夹):

.
├── package.json
├── package-lock.json
├── public
│   └── index.html
└── src
    ├── App.js
    ├── Checkbox.js
    ├── index.css
    ├── index.js
    ├── TableBody.js
    ├── TableHeader.js
    └── Table.js

index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>React App</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import 'bootstrap/dist/css/bootstrap.min.css';

ReactDOM.render(<App />, document.getElementById('root'));

App.js

import { Component } from "react";
import Table from "./Table"

class App extends Component {
  render() {
    const tasks = [
      {
        status: "incomplete",
        task: "Wash Dishes"
      },
      {
        status: "complete",
        task: "Pat Dog"
      },
      {
        status: "incomplete",
        task: "Study"
      }
    ]

    return (
      <div>
        <Table tasks={tasks}/>
      </div>
    )
  }
}

export default App;

Table.js:

import TableHeader from "./TableHeader"
import TableBody from "./TableBody"
import { Component } from "react"

class Table extends Component {
    render () {
        const {tasks} = this.props
        return (
            <div className="table container">
                <TableHeader />
                <TableBody tasks={tasks}/>
            </div>

        )
    }
}

export default Table

TableBody.js

import Checkbox from './Checkbox'

const TableBody = (props) => {
    // takes the properties of the Table object and creates table rows by mapping
    // elements in the array. Returns a table body.

    const rows = props.tasks.map((row, index) => {
        return (
            <tr key={index}>
                <td><Checkbox /></td>
                <td>{row.task}</td>
            </tr>
        )
    })

    return <tbody>{rows}</tbody>
} 

export default TableBody

TableHeader.js

const TableHeader = () => {
    return (
        <thead>
            <tr>
                <th>Status</th>
                <th>Task</th>
            </tr>
        </thead>
    )
}

export default TableHeader

Checkbox.js

const checkStatus = (checked) => {
    var status = "Something's gone wrong."
    if (checked) {
        var status = "Complete"
    } else if (checked == false) {
        var status = "Incomplete"
    } else {
    }
    return status
}

const Checkbox = () => {
    const input = <input class="form-check-input" type="checkbox" checked></input>
    const status = checkStatus(input.props.checked)
    return (
        <div class="custom-control custom-textbox">
            {input}
            <label>{status}</label>
        </div>
    )
}

export default Checkbox

所以您需要一些状态,以便您的应用程序可以“记住”复选框应该处于什么状态。该状态将根据复选框是否被单击而改变。目前,您正在将选中状态设置为始终为真(因此它将始终显示为已选中)。尝试像这样添加一些状态:

import React, { useState } from 'react';

...

const Checkbox = () => {

  const [isChecked, setIsChecked] = useState(false);
  const Input = (
    <input
      class="form-check-input"
      type="checkbox"
      checked={isChecked}
      onClick={() => setIsChecked(!isChecked) }
    />
    // You can self close tags in React fyi, unlike in HTML.
  ); 

  return (
        <div class="custom-control custom-textbox">
            <Input />
            <label>isChecked is set to: {isChecked}</label>
        </div>
  );
}

发生的事情是,每次单击复选框时,它都会将 isChecked 状态更改为与当前状态相反的状态。如果它是假的,它就会变成真的,反之亦然。然后,您可以将此值提供给应用程序的其他部分,以实际 使用 复选框的值(例如在服务器提交中)。

我应该提一下——这使用了 React useState 挂钩。有许多其他方法可以将状态管理引入您的应用程序,但这可能是最简单的一种。您可以在这里阅读:https://reactjs.org/docs/hooks-state.html