简体   繁体   中英

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. I couldn't make it work yet.

I guess my onChange event is not right ( 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.)

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 = (e) => {
 this.setState({
  eligibleAge: e.target.value
 })
}

And you can use this.state.eligibleAge to shoe true/false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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