繁体   English   中英

将对象数组传递给 React 中的样式道具和 TypeScript

[英]Pass array of objects to style prop in React and TypeScript

在 JavaScript React 中,我会这样做来“合并”几个 styles:

const customStyle= {
    fontWeight: 'bold'
};

<p 
    style={[{fontStyle: 'italic'}, customStyle]}>
    {Some Text....}
</p>

但是,当我在 TypeScript React 项目中尝试此操作时,我得到以下信息:

TS2322: Type '({ fontWeight: string; } | { fontStyle: string; })[]' is not assignable to type 'Properties<string | number, string & {}>'.
   Types of property 'filter' are incompatible.
     Type '{ <S extends { fontWeight: string; } | { fontStyle: string; }>(predicate: (value: { fontWeight: string; } | { fontStyle: string; }, index: number, array: ({ fontWeight: string; } | { fontStyle: string; })[]) => value is S, thisArg?: any): S[]; (predicate: (value: { ...; } | { ...; }, index: number, array: ({ ...; } ...' is not assignable to type 'Filter | undefined'.

这个数组结构非常方便,因为元素的顺序很重要。 使用customStyle我可以覆盖我之前在 object {fontStyle: 'italic'}中定义的所有内容......

我如何将几个 styles 传递给 HTML 元素的style道具?

你为什么不使用传播运营商? 像这样:

style={{fontStyle: 'italic', ...customStyle}}

您的 styles 也将以这种方式被覆盖

您需要将数组缩减为单个 object:

style={[{fontStyle: 'italic'}, customStyle].reduce((carry, current) => ({ ...carry, ...current}), {})}

react中的style属性可以接收React.CSSProperties | undefined React.CSSProperties | undefined , React.CSSProperties 类型的React.CSSPropertiesundefined但不是数组。

您可以使用 reducer 将数组中的两个对象合并为一个对象,或者使用类型为React.CSSProperties的两个对象的扩展运算符。

要“覆盖”一个 object,只需在其后放置扩展运算符,所有重复的键都将被覆盖。

const customStyle: React.CSSProperties = {
  fontStyle: "normal",
  fontWeight: "bold"
};

<p
  style={{
    fontStyle: "italic",
    ...customStyle
  }}
>
  Some text
</p>

沙盒

暂无
暂无

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

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