首页 > 解决方案 > 使用状态变量重新渲染 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。所以,第一个块(密码部分)被渲染。没问题。并且与普通输入和按钮相同,它被样式化并作为另一个组件保存。所以没有相关的问题

问题是当我在用户名部分的输入中输入名称并单击按钮时,相同的名称出现在密码部分的输入中?如何使其为空输入以允许用户提交密码

标签: javascriptreactjsforms

解决方案


您应该通过将值保持在组件状态来控制输入。并在输入集本地状态发生变化时。像这样的东西。

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) } />
            </>
    }
);

推荐阅读