简体   繁体   English

如何在 React 的数据预览中显示复选框布尔值?

[英]How to display a checkbox boolean value in a data preview in React?

I'm trying to set up a checkbox in React so that it would display a boolean ( true / false or checked / unchecked ) in a data preview box.我正在尝试在 React 中设置一个复选框,以便它在数据预览框中显示一个布尔值( true / falsechecked / unchecked )。 I couldn't make it work yet.我还不能让它工作。

I guess my onChange event is not right ( handleOnChangeAgreementCheckbox ).我想我的onChange事件不正确( handleOnChangeAgreementCheckbox )。 How do I fix that?我该如何解决?

Demo on codesandbox代码沙盒上的演示

Code代码

          <Input
            name="eligibleAge"
            type="checkbox"
            label="I agree"
            checked={this.state.active}
            value={this.state.checked}
            onChange={(e) => {
              this.handleOnChangeAgreementCheckbox({
                target: {
                  name: e.target.name,
                  value: e.target.checked,
                },
              });
            }}
          />

Desired Output in Data Preview:数据预览中的期望输出:

    "eligibleAge": true

or或者

    "eligibleAge": "checked"

(Thanks! I'm new to React framework.) (谢谢!我是 React 框架的新手。)

It looks like you might be using the wrong component for your checkbox.看起来您的复选框可能使用了错误的组件。 Try this:尝试这个:

Change this line:改变这一行:

import { Input, Button } from "react-advanced-form-addons";

to:到:

import { Input, Button, Checkbox } from "react-advanced-form-addons";

And then change your checkbox render code from this:然后从此更改您的复选框渲染代码:

<Input
  name="eligibleAge"
  type="checkbox"
  label="I agree"
  checked={this.state.active}
  value={this.state.checked}
  onClick={() => this.handleOnChangeAgreementCheckbox()}
/>

to this:对此:

<Checkbox
  name="eligibleAge"
  label="I agree"
  checked={this.state.eligible}
/>

I will use your input as example:我将使用您的输入作为示例:

            name="eligibleAge"
            type="checkbox"
            label="I agree"
            checked={this.state.active}
            value={this.state.checked}
            onClick={() => this.handleOnChangeAgreementCheckbox()}
          />

handleOnChangeAgreementCheckbox function: handleOnChangeAgreementCheckbox 函数:

handleOnChangeAgreementCheckbox = (e) => {
 this.setState({
  eligibleAge: e.target.value
 })
}

And you can use this.state.eligibleAge to shoe true/false你可以使用this.state.eligibleAge来判断真/假

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

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