本文介绍了在React中使用道具进行干燥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个组成部分.我们称之为< MyComponent> .它在十几个不同的文件中使用.我们想更改此组件的样式.幸运的是,该组件公开了一个 stylingProps 属性.因此,我们在十几个文件中的每个文件中都写了以下内容:

We have a component. Let's call it <MyComponent>. It is being used in a dozen different files. We wanted to change the styling on this component. Fortunately, the component exposes a property stylingProps. So, we wrote the following in each of the dozen files:

public render() {
   const styles = {color: "purple", background: "gold"}
   return(
      <MyComponent
          otherPropsUniqueToEachfile={"somethingOrOther"}
          styles={styles}
      >
         "Some text"
      </MyComponent>
   )}

我应该如何重构它,以免在十几个不同的文件中不添加具有完全相同值的常量 styles ?这样做的反应方式"是什么?

How should I refactor this so that I am not adding the constant styles with the exact same values in a dozen different files? What is "the React Way" to do so?

推荐答案

我喜欢为应用创建通用组件,该组件使用内部的库组件.我的应用程序的其余部分使用这些通用组件,而无需任何外部库组件知识.然后,我可以使用通用组件创建一个界面,我的应用程序可以使用该界面来控制其在不同状态下的外观或行为.

I like to create common components for the app, which use the library components under the hood. The rest of my app uses these common components without any knowledge of the external library component. Then, I can use my common component to create an interface that my app can use to control its appearance or behavior in different states.

例如,让我们假设您的< MyComponent> 是一个来自组件库的按钮.在此示例中,让我们假设您的应用具有三个按钮变体,我将它们称为主要",次要"和默认".

For example, let's pretend your <MyComponent> is a button coming from a component library. In this example, let's pretend your app has three button variants, that I'll call "primary", "secondary", and "default".

目标是在您的应用中,您可以导入自定义的 Button 组件,并按以下方式使用它:

The goal is that in your app, you could import your custom Button component, and use it like this:

<Button variant="primary" arbitraryProp={data}>Button Text</Button>

variant ="primary" 会将颜色/样式设置为特定方式.

And the variant="primary" will color/style it a particular way.

构建用于处理此问题的 Button 组件的一种方法是:

One way to build the Button component to handle this would be:

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} />;
}

我喜欢创建一个像这样的图层,它位于组件库和我的应用程序的其余部分之间.这样可以轻松创建自定义控件,而且还可以在不更改所有使用组件的文件的情况下换出新的组件库.

I like creating a layer like this that sits between component libraries and the rest of my app. It makes it easy to create custom control like this, but also to swap out a new component library down the road without having to change all of the files that use components.

这篇关于在React中使用道具进行干燥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 08:53