【问题标题】:Changing tooltip icon on field condition更改字段条件的工具提示图标
【发布时间】:2021-08-27 12:48:40
【问题描述】:

我正在尝试为 INPUT 字段实现一个工具提示,它应该在某些情况下更改图标。 最基本的用法是注册表单上的密码字段。 需要有关如何正确执行此操作的建议。

目前我有:

      <Tooltip title={<div><ArrowRightIcon /> 8 characters<br /> <ArrowRightIcon /> 1 letter <br /> <ArrowRightIcon /> 1 special symbol<br /><ArrowRightIcon /> 1 number</div>} arrow>


      <Input
        
        id="standard-adornment-password"
        type={values.showPassword ? 'text' : 'password'}
        value={values.password}
        onChange={handleChange('password')}
        
        endAdornment={
          <InputAdornment position="end">
            <IconButton
              aria-label="toggle password visibility"
              onClick={handleClickShowPassword}
              onMouseDown={handleMouseDownPassword}
            >
              {values.showPassword ? <Visibility /> : <VisibilityOff />}
            </IconButton>
          </InputAdornment>
        }
      />
      </Tooltip>

一旦条件为真,我希望将“ArrowRightIcon”图标更改为“CheckIcon”。

请协助正确实施。

【问题讨论】:

  • 您始终可以在 JSX 中的任何位置使用三元表达式:{var ? &lt;TrueIcon /&gt; : &lt;FalseIcon /&gt;}

标签: javascript reactjs react-native material-ui


【解决方案1】:

这里仍然可以进行一些改进,但总体思路是这样的:

<Tooltip title={<div>
    { values.password.length >= 8 ? <ArrowRightIcon /> : <CheckIcon /> }
    { /* Repeat for your other conditions. */ }
</div>}>
...
</Tooltip>

如果您想真正花哨并避免代码重复,您可以设置一个谓词数组并遍历它们:

const passwordChecks = [
    { check: (password) => password.length >= 8, message: "8 characters" },
    // ...
];
<Tooltip title={<div>{passwordChecks.map(check => <span>
    {check.validate(password) ? <ArrowRightIcon /> : <CheckIcon />}{" "}
    {check.message}
</span>)}</div>}>
...
</Tooltip>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-02
    • 1970-01-01
    • 2018-12-25
    • 1970-01-01
    • 2016-12-13
    • 2011-06-23
    • 2023-03-16
    • 1970-01-01
    相关资源
    最近更新 更多