我正在构建一个 CMS 系统来管理营销登陆页面。在“编辑登陆页面”视图上,我希望能够加载用户正在编辑的任何登陆页面的关联样式表。我怎样才能用 React 做这样的事情呢?
我的应用程序是完全 React、同构的、运行在Koa。我的相关页面的基本组件层次结构如下所示:
App.jsx (has `<head>` tag)
└── Layout.jsx (dictates page structure, sidebars, etc.)
└── EditLandingPage.jsx (shows the landing page in edit mode)
登陆页面的数据(包括要加载的样式表的路径)是异步获取的EditLandingPage
in ComponentDidMount
.
如果您需要任何其他信息,请告诉我。很想弄清楚这一点!
奖励:我还想在离开页面时卸载样式表,我认为我可以执行与我收到的任何答案相反的操作ComponentWillUnmount
, right?
只需使用 React 的状态更新您想要动态加载的样式表路径即可。
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)