React-如何在 TextField 具有值时启用按钮

发布于 2025-01-09 15:42:52 字数 293 浏览 3 评论 0原文

因此,我尝试在文本字段中输入值后立即启用按钮。启用它的唯一方法是在将值放入文本字​​段后单击文本字段外部。我知道我错过了一些小东西,但我仍然没有找到正确的方法。我将不胜感激你的建议。

TextField 和 LoadingButton 的代码

窗口

So I'm trying to enable a button as soon as I enter a value in the TextField. The only way it is enabled is if i click outside the TextField after I put a value inside the Textfield. I know i'm missing something small but I still haven't found the correct way. I would appreciate your advice .

The code for the TextField and LoadingButton

the Window

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

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

发布评论

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

评论(2

幼儿园老大 2025-01-16 15:42:52

我只包含了相关部分。

import { useState } from "react";

export default function Home() {
  const [name, setName] = useState("");

  const hanldeUserInput = (e) => {
    setName(e.target.value);
  };

  return (
    <Dialog>
      <TextField onChange={hanldeUserInput} value={name} />

      <LoadingButton disabled={name === ""}>Save</LoadingButton>
    </Dialog>
  );
}

I have included only the relevant part.

import { useState } from "react";

export default function Home() {
  const [name, setName] = useState("");

  const hanldeUserInput = (e) => {
    setName(e.target.value);
  };

  return (
    <Dialog>
      <TextField onChange={hanldeUserInput} value={name} />

      <LoadingButton disabled={name === ""}>Save</LoadingButton>
    </Dialog>
  );
}
浪荡不羁 2025-01-16 15:42:52

您可以跟踪文本字段中的当前值并将其存储在状态中。

const [txtFieldValue, setTxtFieldValue] = useState<string>('')

并编写一个在文本字段中的更改事件上触发的函数:

function handleTxtFieldChange(event) {
    if (event.target.id === 'myTextFieldId') {
      setTxtFieldValue(event.target.value)
    }
  }

然后您可以调整文本字段:

      <TextField
        id={'myTextFieldId'}
        // ... all your other stuff
        onChange={(event) => {
          handleTxtFieldChange(event)
        }}
      />

然后您可以使用 set txtFieldValue 来呈现按钮,如下所示:

{txtFieldValue != '' ? <Button /> : <></>}

或者如果您只想禁用它,您可以使用

txtFieldValue != ''

作为布尔值。

You could keep track of the current value inside your textfield and store it inside the state.

const [txtFieldValue, setTxtFieldValue] = useState<string>('')

and write a function which is triggered on the change event in your textfield:

function handleTxtFieldChange(event) {
    if (event.target.id === 'myTextFieldId') {
      setTxtFieldValue(event.target.value)
    }
  }

And then you can adjust your textfield:

      <TextField
        id={'myTextFieldId'}
        // ... all your other stuff
        onChange={(event) => {
          handleTxtFieldChange(event)
        }}
      />

and you can then use the set txtFieldValue to render the button like:

{txtFieldValue != '' ? <Button /> : <></>}

or if you just want to disable it you can just use the

txtFieldValue != ''

as a boolean.

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