如何通过为输入标签分配状态来禁用 React 中的输入标签
How to disable an Input tag in React by assigning a state to an Input tag
我正在使用 React 进行设计,我正在使用 Ant 设计,我的问题是我有一个具有三个 Input 标签的表单。根据 Ant design,我知道如何禁用 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
只需要将true/false传给Input组件的disabled属性即可。如果 disableUsername 包含一个布尔状态,那么你可以用它来切换。
<Input
// This is where you want to disable your UI control
disabled={disableUsername}
placeholder="Username"
/>
我正在使用 React 进行设计,我正在使用 Ant 设计,我的问题是我有一个具有三个 Input 标签的表单。根据 Ant design,我知道如何禁用 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
只需要将true/false传给Input组件的disabled属性即可。如果 disableUsername 包含一个布尔状态,那么你可以用它来切换。
<Input
// This is where you want to disable your UI control
disabled={disableUsername}
placeholder="Username"
/>