【问题标题】:Error in React form re-rendering using a state variable使用状态变量重新渲染 React 表单时出错
【发布时间】:2023-03-18 03:12:01
【问题描述】:
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。因此,第一个块(密码部分)被渲染。没问题。 与普通输入和按钮相同,被样式化并作为另一个组件保存。所以没有相关的问题

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

【问题讨论】:

标签: javascript reactjs forms


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2020-04-22
    • 2016-12-22
    • 2019-08-30
    • 2020-01-20
    • 2018-12-31
    • 2020-11-05
    • 1970-01-01
    • 1970-01-01
    • 2019-09-15
    相关资源
    最近更新 更多