【问题标题】:I can't write in my inputs text using Reactjs and TypeScript我无法使用 Reactjs 和 TypeScript 在我的输入文本中写入
【发布时间】:2020-08-26 03:51:14
【问题描述】:

就我的代码而言,我认为我做的事情是正确的。在这一刻,我无法在输入中写入。有人知道会发生什么吗?下面附上我的代码:

const Login: SFC<LoginProps> = ({ history }) => {
    const alertContext = useContext(AlertContext);
    const { alert, showAlert } = alertContext;
    const authContext = useContext(AuthContext);
    const { message, auth, logIn } = authContext;
    useEffect(() => {
        if (auth) {
            history.push('/techs');
        }
        if (message) {
            showAlert(message.msg, message.category);
        }
    }, [message, auth, history]);
    const [user, saveUser] = useState({
        email: '',
        password: ''
    });
    const { email, password } = user;
    const onChange = (e: any) => {
        saveUser({
            ...user,
            [e.target.name]: e.target.value
        })
    }
    const onSubmit = (e: any) => {
        e.preventDefault();
        if (email.trim() === '' || password.trim() === '') {
            showAlert('All fields are required', 'alert-error');
        }
        logIn({ email, password });
    }

    return (
        <>
            ...
                    <form onSubmit={onSubmit}>
                        <input type="text" ... value={email} onChange={onChange} />
                        <input type="password" ... value={password} onChange={onChange} />
                        <input type="submit" className="fadeIn third" value="Log In" />
                    </form>
            ...
        </>
    );
}

export default Login;

这就是组件的样子:

【问题讨论】:

  • 你的输入中有名字吗?

标签: reactjs typescript forms input


【解决方案1】:

一定是因为你的 onChange 没有按照你期望的方式工作,所以 email 的价值永远不会改变。

我可以看到两个可能的问题。

  1. 在您的 onChange 中,为什么要将 e.target.value 保存到 e.target.name?除非名称 prop 在您的代码中,但您将其作为省略号的一部分省略了。在这种情况下,它可能是第 2 位:
  2. 尝试将电子邮件和密码作为单独的状态片段(通过单独调用 useState 创建的字符串)。这将需要两个更改处理程序(或一个更有创意的单个处理程序,如果您确实有一个名称道具,那么您当前的处理程序可能已经工作。如果名称道具正在工作)。无论如何,您永远不会使用用户对象,这可能/很可能实际上是您的实际问题(不仅仅是最佳实践)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-25
    • 2021-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-07
    • 2021-05-09
    • 2019-06-16
    相关资源
    最近更新 更多