使用React动态加载样式表 [英] Dynamically load a stylesheet with React

查看:1615
本文介绍了使用React动态加载样式表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个用于管理营销目标网页的CMS系统。在编辑登录页面视图中,我希望能够为用户正在编辑的任何登录页面加载相关的样式表。我怎么能用React做这样的事情呢?

I'm building a CMS system for managing marketing landing pages. On the "Edit Landing Page" view, I want to be able to load the associated stylesheet for whichever landing page the user is editing. How could I do something like this with React?

我的应用程序是完全反应,同构,运行在兴亚。我对该页面的基本组件层次结构看起来像这样:

My app is fully React, isomorphic, running on Koa. My basic component heirarchy for the page in question looks something like this:

App.jsx (has `<head>` tag)
└── Layout.jsx (dictates page structure, sidebars, etc.)
    └── EditLandingPage.jsx (shows the landing page in edit mode)

着陆页的数据(包括要加载的样式表的路径)是在 EditLandingPage ComponentDidMount

Data for the landing page (including the path of the stylesheet to load) is fetched asynchronously in EditLandingPage in ComponentDidMount.

如果您需要任何其他信息,请告诉我。很想得到这个想法!

Let me know if you need any additional info. Would love to get this figured out!

奖励:我还想在离开页面时卸载样式表,我认为我可以反过来在 ComponentWillUnmount ,无论回答什么,对吗?

Bonus: I'd also like to unload the stylesheet when navigating away from the page, which I assume I can do the reverse of whatever answer comes my way in ComponentWillUnmount, right?

推荐答案

只是更新要使用react的状态动态加载的样式表路径。

Just update stylesheet's path that you want to be dynamically loaded by using react's state.

import * as React from 'react';

export default class MainPage extends React.Component{
    constructor(props){
        super(props);
        this.state = {stylePath: 'style1.css'};
    }

    handleButtonClick(){
        this.setState({stylePath: 'style2.css'});
    }

    render(){
        return (
            <div>
                <link rel="stylesheet" type="text/css" href={this.state.stylePath} />
                <button type="button" onClick={this.handleButtonClick.bind(this)}>Click to update stylesheet</button>
            </div>
        )
    }
};

此外,我已将其实施为反应组件。您可以通过npm install react-dynamic-style-loader安装。

检查我的github存储库以检查:
https:// github.com/burakhanalkan/react-dynamic-style-loader

Also, I have implemented it as react component. You can install via npm install react-dynamic-style-loader.
Check my github repository to examine:
https://github.com/burakhanalkan/react-dynamic-style-loader

这篇关于使用React动态加载样式表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆