javascript - 使用状态变量重新渲染 React 表单时出错
问题描述
const [ usernameBox , setUsernameBox ] = useState(false);
return(
{
usernameBox ?
<>
<div style={{ fontSize:"25px" }}>{"Sign up with Security"}</div>
<TileInput placeholder={"Enter Password"} />
<TileButton value={"Confirm"} />
</>
:<>
<div style={{ fontSize:"25px" }}>{ ("Sign up"}</div>
<TileInput placeholder={"Enter username"} />
<TileButton value={"Continue"} onClick={ () => setUsernameBox(true) } />
</>
}
);
这里有两个表格块。当 usernameBlock 为 false 时,将呈现第二个块(用户名部分)。当用户输入输入并单击按钮 usernameBlock 的值更改为 true。所以,第一个块(密码部分)被渲染。没问题。并且与普通输入和按钮相同,它被样式化并作为另一个组件保存。所以没有相关的问题
问题是当我在用户名部分的输入中输入名称并单击按钮时,相同的名称出现在密码部分的输入中?如何使其为空输入以允许用户提交密码
解决方案
您应该通过将值保持在组件状态来控制输入。并在输入集本地状态发生变化时。像这样的东西。
const [ usernameBox , setUsernameBox ] = useState(false);
const [ name , setName ] = useState("");
const [ password , setPassword ] = useState("");
return(
{
usernameBox ?
<>
<div style={{ fontSize:"25px" }}>{"Sign up with Security"}</div>
<input placeholder={"Enter Password"} value={password} onChnage={(e)=> setPassword(e.target.value)}/>
<Button value={"Confirm"} />
</>
:<>
<div style={{ fontSize:"25px" }}>{ ("Sign up"}</div>
<input placeholder={"Enter username"} value={name} onChnage={(e)=> setName(e.target.value)}/> />
<Button value={"Continue"} onClick={ () => setUsernameBox(true) } />
</>
}
);
推荐阅读
- r - 带有表格 ggplot 编码的森林图
- c# - 如何在整个应用程序中创建和注入用户特定的单例类?
- c++ - 我正在尝试实现典型的最低成本路径问题。但是我无法处理给定的 Struct 类和 ENUM 类型我该如何处理?
- php - 在 PHP 中使用 domDocument 获取部分文本
- ios - react-native auth0 用苹果登录?
- python - 拟合统计分布 cdf 函数
- file-upload - 如何使用rest api为用户分配nuxeo中特定文件夹的权限
- c# - 从 C# 返回输出参数
- android - Android生命周期与iOS生命周期比较
- bazel - 我可以在宏的上下文中扩展 glob 吗?