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

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

问题描述

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

我的应用完全是 React、同构的,在 Koa 上运行.我的相关页面的基本组件层次结构如下所示:

App.jsx(有 `` 标签)└── Layout.jsx(决定页面结构、侧边栏等)└── EditLandingPage.jsx(在编辑模式下显示登陆页面)

登录页面的数据(包括要加载的样式表的路径)在 ComponentDidMount 中的 EditLandingPage 中异步获取.

如果您需要任何其他信息,请告诉我.很想弄清楚这一点!

奖励:我还想在离开页面时卸载样式表,我假设我可以对 ComponentWillUnmount 中出现的任何答案进行反向操作,对吗?

解决方案

只需使用 react 的 state 更新要动态加载的样式表的路径.

import * as React from 'react';导出默认类 MainPage 扩展 React.Component{构造函数(道具){超级(道具);this.state = {stylePath: 'style1.css'};}处理按钮点击(){this.setState({stylePath: 'style2.css'});}使成为(){返回 (<div><link rel="stylesheet" type="text/css" href={this.state.stylePath}/><button type="button" onClick={this.handleButtonClick.bind(this)}>点击更新样式表</button>

)}};

此外,我已将其实现为 react 组件.你可以通过 npm install react-dynamic-style-loader 安装.
检查我的 github 存储库以检查:
https://github.com/burakhanalkan/react-dynamic-style-loader

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)

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!

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?

解决方案

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

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天全站免登陆