You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React JSX未根据用户密码输入返回指定图标或文本问题求助

修复密码输入框末尾提示/图标不显示的问题

你的密码输入框末尾没有内容显示,是因为代码里存在三个关键错误:

  • 匿名函数未执行:你在endAdornment中定义了一个匿名函数,但没有调用它,React只会将函数本身视为节点,不会渲染函数返回的内容。
  • 字符串长度调用错误:state.users.password.length()写法错误,字符串的长度是属性而非方法,应该用state.users.password.length。
  • 直接返回纯文本:InputAdornment的子元素必须是React元素,不能直接返回原始字符串,需要用标签或组件包裹。

修复后的代码

<TextField 
  className="users-password-input" 
  required={true} 
  label='Password' 
  InputProps={{ 
    startAdornment: (
      <InputAdornment position='start'>
        <LockSharpIcon color="primary"/>
      </InputAdornment>
    ),
    endAdornment: (
      <InputAdornment position="end">
        {state.users?.password && state.users.password.length >= 12 ? (
          <CheckCircleIcon color="success" />
        ) : (
          <span style={{ fontSize: '0.875rem', color: '#d32f2f' }}>
            您的密码必须至少12个字符
          </span>
        )}
      </InputAdornment>
    )
  }} 
  onChange={(e) => dispatch(createUsers(e.target.value, 'password'))}
/>

修复说明

  1. 移除匿名函数,改用三元表达式直接进行条件渲染,React会自动解析并渲染对应内容。
  2. 修正length的调用方式,从length()改为length,正确获取密码字符串的长度。
  3. 用<span>包裹提示文本,并添加了匹配MUI风格的基础样式,确保是合法的React节点。
  4. 增加了可选链state.users?.password,避免state.users未初始化时出现报错。

内容的提问来源于stack exchange,提问作者SupraCoder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 20:27:25