reactjs - 为什么我在 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
`;
解决方案
问题是原生的input
并且Input
具有不兼容的ref
属性类型。虽然本机input
ref
有类型
LegacyRef<HTMLInputElement> | undefined
styled-components
包裹Input
有ref
类型
((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" />
);
推荐阅读
- java - 生成总和为 N 的数字的所有排列
- c - 将exe反编译映射回C语言
- r - 乘以 R 增加的百分比
- python - pd.read_html 读取一个空表
- amazon-ec2 - Amazon aws route53,将子域重定向到在特定端口下运行的 ec2 应用程序
- c# - 如何检查子模型状态是否有效,而不是检查 asp.net 核心中的主模型状态?
- android - Android片段ClassNotFoundException:找不到类android.support.constraint.ConstraintLayout
- tcl - 如何在 TCL 脚本中将字符串从说英语翻译成日语
- c# - 方法“ImageAnnotatorClient.Create”没有重载需要 1 个参数
- android - Android Java 与 Native C 未定义的对 `__android_log_print' 的引用