【问题标题】:This condition will always return 'false' since the types 'MutableRefObject<string | null>' and 'string' have no overlap. TS2367此条件将始终返回 'false',因为类型 'MutableRefObject<string | null>' 和 'string' 没有重叠。 TS2367
【发布时间】:2021-01-31 20:15:28
【问题描述】:

我有问题 使用 React 和 TS

我在美国有电子邮件和密码的状态

const emailRef = useRef<string | null>(null);
const passwordRef = useRef<string | null>(null);

像这样设置它们:

const onEmailChange = (value: any) => {
        emailRef.current = value;
    };

    const onPasswordChange = (value: any) => {
        passwordRef.current = value;
    };

并尝试使用它们的 onButtonEnter 函数对接得到这个问题:

const onButtonEnter = () => {
        if (!buttonDisabled) {
            setButtonDisabled(true);
            if (emailRef === '' && passwordRef === '') { - here I have an issue
                showAlert(errors.invalid);

!!!此条件将始终返回 'false',因为类型 'MutableRefObject' 和 'string' 没有重叠。 TS2367

它可能是什么?

【问题讨论】:

  • 您正在比较对 DOM 元素的引用和字符串,这没有意义。

标签: javascript reactjs typescript


【解决方案1】:

您的问题的答案在错误消息中:

  • emailRef 是一个反应对象 - 'MutableRefObject&lt;string | null&gt;'
  • emailRef.current 是你的字符串

emailRef 永远不会是'',另一方面,emailRef.current 很可能是。

改变

if (emailRef === '' && passwordRef === '') {

进入

if (emailRef.current === '' && passwordRef.current === '') {

也许,在 React 文档中阅读更多关于 useRef 的内容。

【讨论】:

    猜你喜欢
    • 2019-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    • 2020-12-11
    • 2020-01-05
    • 1970-01-01
    相关资源
    最近更新 更多