React.js 在所属输入字段旁边显示错误消息

时间:2021-03-21 12:50:49

标签: javascript html css reactjs

我已经用 Django 和 React.js 创建了一个 API 登录/注册系统,我已经启动并运行了我的后端,注册系统本身功能齐全,我现在需要的是一种在之后显示响应消息的方法从 React.js 到 Django 的 API 调用。 API调用后的所有错误都作为对象存储在状态中。到目前为止,我只是显示了这样的所有消息:

enter image description here

我现在需要的是一种让它们看起来像这样的方法:

enter image description here

所以基本上错误信息本身的 JSX 代码是:

<small style={{color: '#ea0027',marginBottom: '0.5rem',fontWeight: 'bold',}}>
    <li style={{ listStyleType: 'circle' }}>{name} {error}</li>
</small>

这就是我现在呈现消息的方式:

 {Object.entries(this.state.errors).map(([name, error]) => (
     <small style={{color: '#ea0027',marginBottom: '0.5rem',fontWeight: 'bold'}}>
        <li style={{ listStyleType: 'circle' }}>{name} {error}</li>
     </small>
  ))}

1 个答案:

答案 0 :(得分:0)

也许是这样的。我不知道 this.state.error 中的数据看起来如何,所以也许您可以像本例中那样从错误中选择它

  {Object.entries(this.state.errors).map(([name, error]) => (
   return (
                <>
           <li style={{ listStyleType: "circle" }}>
            <RegisterInput
              type="text"
              invalid={true}
              name="username"
              value={this.state.username}
              placeholder="Choose a username"
              autoComplete="new-username"
              onChange={(e) => this.onChange(e)}
              pattern="^(?=[a-zA-Z0-9._]{3,20}$)(?!.*[_.]{2})[^_.].*[^_.]$"
            />
             {error.username}
          </li>
         <li style={{ listStyleType: "circle" }}>
            <RegisterInput
              type="email"
              name="email"
              value={this.state.email}
              autoComplete="new-email"
              placeholder="Enter your email address"
              onChange={(e) => this.onChange(e)}
            />
            {error.email}
          </li>
          <li style={{ listStyleType: "circle" }}>
             <RegisterInput
              type="password"
              name="password"
              value={this.state.password}
              placeholder="Password"
              autoComplete="new-password"
              onChange={(e) => this.onChange(e)}
            />
            {error.password}
          </li>
          <li style={{ listStyleType: "circle" }}>
            <RegisterInput
              type="password"
              name="re_password"
              value={this.state.re_password}
              placeholder="Confirm password"
              autoComplete="new-re-password"
              onChange={(e) => this.onChange(e)}
            />
            {error.re_password}
          </li>
         </>
       )
      ))}