如何在输入字段中设置有条件禁用?

发布于 2025-02-02 16:25:07 字数 222 浏览 3 评论 0原文

```<input ref={refName} disabled value={user.displayName} type="text" placeholder="name"  />```

输入字段从UseAuthstate获取其值。我想根据按钮是否按下按钮来禁用该字段。 (例如onclick disable)

```<input ref={refName} disabled value={user.displayName} type="text" placeholder="name"  />```

the input field gets its value from useAuthState. I wanted to disable the field depending on if a button was pressed or not. (like onClick disable)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

萧瑟寒风 2025-02-09 16:25:07

假设这是使用React,您需要跟踪状态,包括是否应该禁用该状态。您不能直接对DOM进行任何修改,因为DOM会反复再生(不是持续的,但有时在您不期望的时候)。

如何执行此操作取决于您是否具有功能组件或类组件,但是底线是将disabled值放入状态,并将该值设置为onclick,然后在渲染中使用该值。

使用ref,通常可以访问生成的元素,通常是从使用>可能不是永久性的,并且可能会重置为dom中较高的元素的渲染启用。

考虑一下此psuedo代码,您可以找到详细信息:


const [isDisabled, setDisabled] = useState(false);

function onClick() {
  setDisabled(true)
}

<input ref={refName} disabled={isDisabled} value={user.displayName} type="text" placeholder="name"  />

<button onClick={onClick}>Disable Input</button>

Assuming this is using React, you need to track the state, including whether it should be disabled. You cannot do any modifications to the DOM directly, as the DOM is regenerated repeatedly (not constantly, but sometimes when you don't expect it).

How to do that depends on if you have a functional component or a class component, but bottom line is, put a disabled value into your state, and set that value in your onClick, then use that value in your render.

Using the ref, it is possible to access the generated element, usually from useEffect, but if you use it from a handler like onClick, it may not be permanent, and might get reset back to enabled by a render of an element higher up in the DOM.

Consider this psuedo code, you can work out details:


const [isDisabled, setDisabled] = useState(false);

function onClick() {
  setDisabled(true)
}

<input ref={refName} disabled={isDisabled} value={user.displayName} type="text" placeholder="name"  />

<button onClick={onClick}>Disable Input</button>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文