簡體   English   中英

React Native,接受原生組件屬性作為道具,並使用 TypeScript 接口自定義屬性

[英]React Native, accept native component properties as props and have custom ones with a TypeScript interface

我有這個AppText組件,我想在其中使用Props接口,同時能夠接受我可以使用spread operator使用的其他 props 字段。 下面是我的嘗試。

應用文本:

import React from "react";
import { View, Text } from "react-native";
import { colors } from "../utils/config";

interface Props {
  fontSize?: number;
  color?: string;
}
const AppText: React.FC<Props> = ({
  children,
  fontSize = 16,
  color = colors.black,
  ...restProps
}) => {
  return (
    <Text {...restProps} style={{ color: color, fontSize: fontSize }}>
      {children}
    </Text>
  );
};

export default AppText;

我如何使用我的組件:

<AppText accessible>Not member yet ? </AppText> 

我得到的錯誤:

Type '{ children: string; accessible: true; }' is not assignable to type 'IntrinsicAttributes & Props & { children?: ReactNode; }'.Property 'accessible' does not exist on type 'IntrinsicAttributes & Props & { children?: ReactNode; }'

您應該能夠重新定義Props ,我假設TextProps可以從react-native導入,如下所示:

interface Props extends TextProps {
  fontSize?: number;
  color?: string;
}

這會將TextProps添加到您的屬性中,展開運算符應該了解剩余的元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM