簡體   English   中英

如何在 React 的數據預覽中顯示復選框布爾值?

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

我正在嘗試在 React 中設置一個復選框,以便它在數據預覽框中顯示一個布爾值( true / falsechecked / unchecked )。 我還不能讓它工作。

我想我的onChange事件不正確( handleOnChangeAgreementCheckbox )。 我該如何解決?

代碼沙盒上的演示

代碼

          <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,
                },
              });
            }}
          />

數據預覽中的期望輸出:

    "eligibleAge": true

或者

    "eligibleAge": "checked"

(謝謝!我是 React 框架的新手。)

看起來您的復選框可能使用了錯誤的組件。 嘗試這個:

改變這一行:

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

到:

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

然后從此更改您的復選框渲染代碼:

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

對此:

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

我將使用您的輸入作為示例:

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

handleOnChangeAgreementCheckbox 函數:

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

你可以使用this.state.eligibleAge來判斷真/假

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM