【问题标题】:How to disable an Input tag in React by assigning a state to an Input tag如何通过将状态分配给 Input 标签来禁用 React 中的 Input 标签
【发布时间】:2021-09-28 17:00:49
【问题描述】:

我正在使用 React 进行设计,我正在使用 Ant 设计,我的问题是我有一个表单,我有三个 Input 标签。根据 Ant 设计,我知道如何禁用 Button 或 Input 标签,但在这里我试图通过状态禁用 Input 标签,但它不起作用。所以请有人帮助我实现这一目标。

这是我尝试过的——App.js

import React, { useState } from "react";
import 'antd/dist/antd.css';
import { Form, Input, Button } from 'antd'
import "./App.css";

const App = () => {
  const [disableUsername, setDisableUsername] = useState(disable)
  return (
    <div style={{marginTop: "100px"}}>
      <Form
      name="basic"
      labelCol={{
        span: 6,
      }}
      wrapperCol={{
        span: 6,
      }}
      initialValues={{
        remember: true,
      }}
    >
      <Form.Item
        label="Username"
        name="username"
        rules={[
          {
            required: true,
            message: 'Please input your username!',
          },
        ]}
      >
        {disableUsername &&
        <Input />
}
      </Form.Item>

      <Form.Item
        label="Email"
        name="email"
        rules={[
          {
            required: true,
            message: 'Please input your email!',
          },
        ]}
      >
        <Input disabled />
      </Form.Item>

      <Form.Item
        label="Password"
        name="password"
        rules={[
          {
            required: true,
            message: 'Please input your password!',
          },
        ]}
      >
        <Input.Password />
      </Form.Item>

      <Form.Item
        wrapperCol={{
          offset: 8,
          span: 16,
        }}
      >
        <Button type="primary" htmlType="submit">
          Submit
        </Button>
      </Form.Item>
    </Form>
    </div>
  )
}

export default App

【问题讨论】:

    标签: reactjs ant-design-pro


    【解决方案1】:

    您只需将 true/false 传递给 Input 组件的 disabled 属性。如果 disableUsername 包含布尔状态,那么您可以使用它进行切换。

    <Input
        // This is where you want to disable your UI control
        disabled={disableUsername}
        placeholder="Username"
    />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-15
      • 2017-03-16
      • 2011-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-31
      相关资源
      最近更新 更多