簡體   English   中英

使用 React Hooks 單擊編輯按鈕時禁用輸入字段

[英]Disable input field when click edit button using React Hooks

我不明白我在這里做錯了什么。 場景是我在用戶配置文件詳細信息上,我想編輯信息,但必須始終禁用一個輸入。 當我加載頁面時,輸入實際上被禁用,但只要我單擊編輯按鈕,它就會像其他輸入的 rest 一樣變得可編輯。 請就如何使其工作提出任何建議?

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

const handleClickEditMember = () => {
  Actions.enableMemberEdit();
  setDisabled(!disabled);
};

<Card className={clsx(classes.root, className)}>
  <CardHeader
    action={
      <Button
        color="primary"
        id="edit-member-button"
        onClick={() => handleClickEditMember()}
        size="small"
        variant="contained"
      >
        {t('members.edit')}
      </Button>
    }
    title={member.companyName}
  />
  <Divider />
  <CardContent className={classes.content}>
    <CardHeader title={t('members.company_profile')} />
    <Grid container spacing={3}>
      <Grid item xs={6}>
        <TextField
          className={classes.textField}
          fullWidth
          id="companyName"
          InputProps={{
            readOnly: true,
          }}
          label={t('members.company_name')}
          margin="dense"
          name="companyName"
          placeholder={t('members.company_name')}
          value={member.companyName}
          variant="outlined"
        />
      </Grid>
      <Grid item xs={3}>
        <TextField
          className={classes.textField}
          fullWidth
          id="Id"
          InputProps={{
            readOnly: true,
          }}
          disabled={!disabled}
          label={t('members.id')}
          margin="dense"
          name="Id"
          placeholder={t('members.id')}
          value={member.id}
          variant="outlined"
        />
      </Grid>
    </Grid>
<TextField
    className={classes.textField}
    fullWidth
    id="Id"
    InputProps={{
        readOnly: true,
    }}
    **disabled**
    label={t('members.id')}
    margin="dense"
    name="Id"
    placeholder={t('members.id')}
    value={member.id}
    variant="outlined"
/>

只需禁用文本字段。 不要為禁用屬性分配任何值

您每次在handleClickEditMember()中通過執行setDisabled(;disabled); 最終將設置為 true,因為它最初是 false。

所以你必須

  • 去掉那段代碼,state更新就不會再觸發了!
  • 對於 ID 輸入字段,只需使用disabled={disabled}

只需這樣做即可解決:

InputProps={{
  readOnly: memberId ? true : false,
}}

暫無
暫無

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

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