React 意外调用函数

这是我的登录组件:


const Login = () => {

    const [user, setUser] = useState("");

    const [pass, setPass] = useState("");


    return (

        <div>

            <p>Login</p>

            <input

                type="text"

                onChange={(e) => {

                    setUser(e.target.value);

                }}

            />

            <input

                type="password"

                onChange={(e) => {

                    setPass(e.target.value);

                }}

            />



            <button onClick={submit(user, pass)}>

                Submit

            </button>

        </div>

    );

};

它呈现在我的网页上,但submit()每当我输入这两个时它都会调用该函数:文本和密码。查看我的代码,我只设置了 onClick 来调用该submit函数。


我的代码有问题吗?


慕妹3242003
浏览 86回答 2
2回答

倚天杖

submit您在每次渲染时都调用该函数。onClick 接受一个函数,但您是直接调用一个函数。<button onClick={submit(user, pass)}>&nbsp; &nbsp;Submit</button>将被替换为<button onClick={()=>submit(user, pass)}>&nbsp; &nbsp;Submit</button>

森栏

尝试 :const Login = () => {&nbsp; &nbsp; const [user, setUser] = useState("");&nbsp; &nbsp; const [pass, setPass] = useState("");&nbsp; &nbsp; const onSubmit = () => {&nbsp; &nbsp; &nbsp; &nbsp;submit(user,pass)&nbsp; &nbsp; }&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <p>Login</p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type="text"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onChange={(e) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setUser(e.target.value);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type="password"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onChange={(e) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setPass(e.target.value);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <button onClick={onSubmit}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Submit&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </button>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; );};
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript