【问题标题】:How to change static css file on API response in ReactJS如何在 ReactJS 中更改 API 响应的静态 css 文件
【发布时间】:2018-12-21 13:07:21
【问题描述】:

在我的项目中,我想更改文本的背景颜色和字体。这两个属性都写在 css 文件中。 项目结构为:

|-myProject
|--public
|--src
|--package.json

我所有的 css 都写在公共目录中,我有一个 api 可以响应背景颜色和字体。现在我想根据api响应更改css文件中的背景颜色和字体属性。

【问题讨论】:

  • 您的应用中这些样式的选项数量是否有限,或者您是否需要能够接受用户向您抛出的任何颜色/字体?
  • 我应该能够接受用户抛出的任何颜色/字体。

标签: node.js reactjs redux react-redux


【解决方案1】:

与其尝试修改基本样式表,不如使用元素的样式属性设置这些特定属性:

const divStyle = {
  backgroundColor: /* Some color */,
  fontFamily: /* Some font stack */,
};

function HelloWorldComponent() {
  return <div style={ divStyle }>Hello World!</div>;
}

改编自the React docs

【讨论】:

  • 但是我必须为每个组件添加样式属性,我想要更改css文件中的属性。
  • @rajatgalav 有一种方法here 基本上相当于创建一个&lt;style&gt; 元素并使用dangerouslySetInnerHTML() 将您的动态CSS 应用到它。这会更像你正在寻找的吗?
【解决方案2】:

我认为最好的方法是在要更改的元素上使用内联样式。 关于 api 响应 -> 设置

const yourVar={ 背景颜色:##, 字体系列:## };

【讨论】:

    【解决方案3】:

    我相信 MTCoster 的答案是最好的方法。根据您的应用程序的结构,您可以使用新的Context API 来制作某种主题提供程序,以便您可以传递可以存储在应用程序状态中并从后端 API 加载的自定义样式。有一些工具可以帮助您更轻松地集成此功能,例如 Styled-Components

    使用 Styled 组件,您可以编写如下内容:

    import styled from 'styled-components'
    import { YourComponentJSX } from '../somewhere'    
    // Wrap the component where you need your custom styles
    const YourStyledComponent = styled(YourComponentJSX)`
      font-size: 1em;
      margin: 1em;
      padding: 0.25em 1em;
      border-radius: 3px;
    
      /* Color the border and text with theme.main */
      // using the short-if to add a default color in case it is not connected to the ThemeProvider
      color: ${props => props.theme.main ? props.theme.main : "palevioletred"};
      border: 2px solid ${props => props.theme.main ? props.theme.main : "palevioletred"};
    `;
    
    // Define what props.theme will look like
    const theme = {
      main: "mediumseagreen"
    };
    
    render(
      <div>
        <ThemeProvider theme={theme}>
          <App>
            <YourStyledComponent>Themed</YourStyledComponent>
          </App>
        </ThemeProvider>
      </div>
    );
    

    这样你可以包装你的整个应用程序并使用保存在从后端加载的应用程序状态中的自定义样式,并将它们用于真正深度嵌套的 ui 组件

    *代码是对 styled-component 文档的修改

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-27
      • 2021-01-17
      • 2022-11-16
      • 1970-01-01
      • 1970-01-01
      • 2019-02-02
      • 2011-10-14
      • 2021-03-09
      相关资源
      最近更新 更多