首页 > 解决方案 > 如何将 typescript 应用于样式化组件,以便在组件上看到推荐的道具?

问题描述

开发人员您好!我正在尝试适应打字稿。

当我习惯了打字稿时,在样式化的组件上看不到推荐的道具有点不方便。

例如,

import {TitleInput} from 'react-native';
import styled from 'styled-components';

const MyStyledInput = styled(TextInput)``;

...

const ExComponent = () => {
  return (
    <TextInput/> // This shows prop recommendations. (ex) onChange, onChangeText, etc)
    <MyStyledInput/> // This doesn't. (no recommendations are shown.)
  )
}

我想我可以通过 using 提供类型React.Element<???>,就像这样:

const MyStyledInput: React.Element<???> = styled(TextInput)``;

但我不确定

  1. 如果这种方法可行,并且,
  2. 如果这可行,那么我应该在<???>.

如何为样式化组件提供类型,以便获得道具推荐?


到目前为止尝试了这些方法

  1. 在回调结束时提供类型
import {TextInput, TextInputProps, TextInputComponent, } from 'react-native';
const MyStyledInput = styled(TextInput)<TextInput>``; // Not working
const MyStyledInput = styled(TextInput)<TextInputProps>``; // Not working
const MyStyledInput = styled(TextInput)<TextInputComponent>``; // Not working


我发现了什么

  1. TextInputProps是我正在寻求实现的目标类型,它具有在react-native 官方网站上列出的道具

标签: reactjstypescriptstyled-components

解决方案


解决方案 React.FC 是功能组件的一种类型。我们可以像这样为 React.FC 提供 prop 类型:React.FC

const MyStyledTextInput: React.FC<TextInputProps> = styled(TextInput)``;
// Now you can see recommendations for TextInputProps.

推荐阅读