В JavaScript React я бы сделал это, чтобы «объединить» несколько стилей:
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 я мог перезаписать все, что я определил в объекте {fontStyle: 'italic'} до...
Как мне передать несколько стилей в style prop HTML-элемента?
@вера. Я делаю это в React-Native все время. Вот один онлайн-пример, который это делает newline.co/30-days-of-react-native/…. Я предположил, что это возможно и в React. Но видимо это не так :)
Вам нужно будет уменьшить массив до одного объекта:
style = {[{fontStyle: 'italic'}, customStyle].reduce((carry, current) => ({ ...carry, ...current}), {})}
Почему вы не используете операторы распространения? так:
style = {{fontStyle: 'italic', ...customStyle}}
Ваши стили также будут перезаписаны таким образом
Я никогда не видел, чтобы это использовалось. У вас есть страница, описывающая это использование?