简体   繁体   English

反应钩子 useRef 不适用于样式组件和 typescript

[英]React hook useRef not working with styled-components and typescript

I've some problem using the useRef hook with a styled component.我在使用带有样式组件的useRef钩子时遇到了一些问题。

Linter alerts me that Object is possibly 'null' inside the didMount useEffect . Linter 提醒我 Object 在 didMount useEffect Object is possibly 'null' Any idea about this?对此有任何想法吗?

This is not a duplicate for 2 reason:这不是重复的,原因有两个:

  • The old answer refers to the ref used in a class component, that was the only way to use it before React hooks,旧答案是指 class 组件中使用的ref ,这是在 React 挂钩之前使用它的唯一方法,
  • The innerRef props isn't supported anymore in the current version of styled components.当前版本的样式化组件不再支持innerRef道具。

Here's a sample snippet of my component:这是我的组件的示例片段:

import React, { useRef, useEffect } from 'react';
import styled from 'styled-components';

const StyledInput = styled.input`
  background: transparent;
`

const MyForm = () => {
  const inputRef = useRef(null);
  
  useEffect(() => {
    if (inputRef && inputRef.current) {
      inputRef.current.focus(); //Object is possibly 'null'
    }
  }, []);

  return (
    <StyledInput ref={inputRef}/>
  );
}

I've finally found a solution:我终于找到了解决方案:

const inputRef = useRef() as React.MutableRefObject<HTMLInputElement>;

It works for me:这个对我有用:

import React, { useRef, useEffect } from 'react';
import styled from 'styled-components';

const StyledInput = styled.input`
  background: transparent;
`

const MyForm = () => {
  const inputRef = useRef() as React.MutableRefObject<HTMLInputElement>;

  useEffect(() => {
    if (inputRef && inputRef.current) {
      inputRef.current.focus();
    }
  }, []);

  return (
    <StyledInput ref={inputRef}/>
  );
}

As an alternative to the current accepted answer, you can also do:作为当前接受的答案的替代方案,您还可以执行以下操作:

const inputRef = useRef<HTMLInputElement>(null);

Pass your inputRef in the array argument of useEffect and let's see if that works, you aren't guaranteed to have a .current in your ref, so you should run the effect every time inputRef changes在 useEffect 的数组参数中传递你的 inputRef ,让我们看看它是否有效,你不能保证你的 ref 中有一个.current ,所以你应该在每次 inputRef 更改时运行效果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM