我们有一个组件。就叫它 <MyComponent>
. 它被用在十几个不同的文件中。我们想改变这个组件的样式。幸运的是,这个组件暴露了一个属性 stylingProps
. 于是,我们在这十几个文件中分别写了以下内容。
public render() {
const styles = {color: "purple", background: "gold"}
return(
<MyComponent
otherPropsUniqueToEachfile={"somethingOrOther"}
styles={styles}
>
"Some text"
</MyComponent>
)}
我应该如何重构这个文件,使我不添加常量。styles
在十几个不同的文件中使用完全相同的数值?什么是 "React方式 "呢?
我喜欢为应用程序创建通用组件,这些组件使用了库中的组件。我的应用程序的其他部分在不知道外部库组件的情况下使用这些通用组件。然后,我可以使用我的通用组件来创建一个接口,我的应用程序可以使用这个接口来控制它在不同状态下的外观或行为。
例如,让我们假设你的 <MyComponent>
是一个来自组件库的按钮。在这个例子中,让我们假设您的应用程序有三个按钮变体,我称之为 "主要"、"次要 "和 "默认"。
我们的目标是,在您的应用程序中,您可以导入您的自定义 "主按钮"、"次按钮 "和 "默认按钮"。Button
组件,并像这样使用它。
<Button variant="primary" arbitraryProp={data}>Button Text</Button>
And the variant="primary"
会以特定的方式进行颜色样式。
构建 Button
组件来处理这个问题。
import ComponentLibraryButton from "component-library";
import React from "react";
function Button({ variant, ...rest }) {
const styles =
variant === "primary"
? { color: "purple", background: "gold" }
: variant === "secondary"
? { color: "green", background: "blue" }
: { color: "black", background: "gray" };
return <ComponentLibraryButton {...rest} styles={styles} />;
}
我喜欢在组件库和应用程序的其他部分之间创建一个这样的层。这使得创建这样的自定义控件很容易,但也可以在以后的道路上更换一个新的组件库,而不必改变所有使用组件的文件。