首页 > 解决方案 > 为什么我在 React + Styled-components 中使用“输入类型”时不能传递道具?

问题描述

我正在学习反应。我想使用样式组件来设置“输入类型”的样式。我可以用普通的“输入类型”扩展道具。但是当我使用 styled-components 时,它不起作用.. props 是从父组件传递的。

import * as React from "react";
import { Input } from "./style";

export const Field: React.FC<React.ComponentProps<"input">> = (
  props: React.ComponentProps<"input">
) => (
  <>
      {/* work */}
    {/* <input {...props} type={"text"} /> */}

      {/* it doesn't work.. */}
      <Input {...props} type={"text"} />     
  </>
);

样式.ts

import styled from "styled-components";

export const Input = styled.input`
 //style
`;

标签: reactjstypescriptstyled-components

解决方案


问题是原生的input并且Input具有不兼容的ref属性类型。虽然本机input ref有类型

LegacyRef<HTMLInputElement> | undefined

styled-components包裹Inputref类型

((instance: HTMLInputElement | null) => void) | RefObject<HTMLInputElement> | null | undefined

如果您不打算将其传递给组件,则可以省略此属性:

export const Field: React.FC<React.ComponentPropsWithoutRef<"input">> = (
  props
) => (
    <Input {...props} type="text" />
);

或正确输入:

@types/react@17.x版本:

type Props = React.ComponentPropsWithoutRef<"input"> & { ref: React.ForwardedRef<HTMLInputElement> }

export const Field: React.FC<Props> = (props) => (
  <Input {...props} type="text" />
);

@types/react@16.x版本:

// there is no exported ForwardedRef type and we have to define it oursevles
type ForwardedRef<T> = ((instance: T | null) => void) | React.MutableRefObject<T | null> | null
type Props = React.ComponentPropsWithoutRef<"input"> & { ref: ForwardedRef<HTMLInputElement> }

export const Field: React.FC<Props> = (props) => (
  <Input {...props} type="text" />
);

推荐阅读