gpt4 book ai didi

javascript - 如何通过带有样式组件的 props 传递样式,而无需在组件内部创建组件

转载 作者:行者123 更新时间:2023-12-01 23:21:56 26 4
gpt4 key购买 nike

如果不在 Text 组件中创建 styled-component,我找不到另一种方法来为 Prop 提供动态样式。为了提高性能,我想在 Text 组件之外创建组件。

样式化组件

import React, { ReactChildren } from 'react'
import styled from 'styled-components'


export const Text = ({ as = 'p', children, styles = {} }) => {
const newStyles = Object.entries(styles).reduce((acc, [key, value]) => {
return `${acc}${key}: ${value};`
}, '')
const Component = styled.p`
${newStyles}
color: #000;
`
return <Component as={as}>{children}</Component>
}

期望的用法

<Text styles={{ height: "10px" }} />

输出HTML

<p styles="height: 10px" />

enter image description here

最佳答案

上面的代码令人困惑,因为您想要将样式应用到 DOM style 属性,但您还将它们作为 CSS 样式应用到类名。无需创建此组合组件,因为 styled-components 无需组合即可处理 aschildrenstyle 属性:

Edit Styled Components - "Styles" Typescript

示例 1:

import React from "react";
import styled, { Interpolation } from "styled-components";

export type TextProps = {
as?: string | React.ComponentType<any>;
children: React.ReactNode;
styles?: Interpolation<React.CSSProperties>;
};

const Component = styled.p<TextProps>`
${({ styles }) => styles}
color: #000;
`;

export const Text = ({
as,
children,
styles
}: TextProps): React.ReactElement => (
<Component styles={styles} as={as}>
{children}
</Component>
);

export default Text;

示例 2:

import styled from "styled-components";

const Text = styled.p`
color: #000;
`;

export default Text;

示例 3:

import * as React from "react";
import styled from "styled-components";

export type TextComponentProps = {
className?: string;
children: React.ReactNode;
styles?: React.CSSProperties;
};

const TextComponent = ({
children,
className,
styles
}: TextComponentProps): React.ReactElement => (
<p className={className} style={styles}>
{children}
</p>
);

const Text = styled(TextComponent)`
color: #000;
`;

export default Text;

用法:

import * as React from "react";
import Box from "./Box";
import Text from "./Text";
import Text2 from "./Text2";
import Text3 from "./Text3";
import "./styles.css";

const App = (): React.ReactElement => (
<div className="app">
<h1>Example 1 - "styles" as CSS Styles</h1>
<Box>
<Text styles={{ height: "10px" }}>Hello</Text>
<Text as="h1">Goodbye</Text>
</Box>
<hr />
<h1>Example 2 - "style" as DOM styles</h1>
<Box>
<Text2 style={{ height: "10px" }}>Hello</Text2>
<Text2 as="h1">Goodbye</Text2>
</Box>
<hr />
<h1>Example 3 - "styles" as DOM styles</h1>
<Box>
<Text3 styles={{ height: "10px" }}>Hello</Text3>
<Text3 as="h1">Goodbye</Text3>
</Box>
</div>
);

export default App;

输出: enter image description here

就此而言,听起来您可能正在尝试做我用 composabled-styled-components 做的事情,虽然我不推荐它,因为它 doesn't work with SSR apps .

关于javascript - 如何通过带有样式组件的 props 传递样式,而无需在组件内部创建组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67990513/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com