这是一个有点主观的问题,但我希望能有所帮助。
我正在制作一个 ReactJS 应用程序,我需要根据数据库中用户的设置自定义样式的某些部分(主要是配色方案)。调色板分布在许多样式表中,因此我希望避免在 render()
方法中手动设置所有这些颜色。
一种选择是在每次请求时在服务器端渲染完整的 css 文件。像 SASS 这样的东西能够实时做到这一点吗?我知道大多数预处理器都是为编译时使用而设计的。
另一种选择是将样式嵌入 JavaScript 模块中,如 react-style 。每个组件“样式表”实际上都可以成为一个函数,它接受一些首选项并返回样式。这种策略有一些缺点(如 here 中所述),此外还需要将“styleSettings”属性传递给每个组件,以便它知道如何请求其样式,从而带来额外的不便。
或者,我可以只有一个全局或页面范围的样式表,这样我就必须处理更少的 Prop ,但我喜欢每个组件都有自己的样式的模块化。
我还缺少其他选项吗?是否有做此类事情的最佳实践?
最佳答案
我不确定这是否是最好的方法,但我使用主题提供程序 HoC 完成了类似的事情。
class ThemeProvider extends React.Component {
componentDidMount() {
// fetch required data if you don't already have it
// create a <style> node
this.styleTag = document.createElement('style')
this.styleTag.type = 'text/css'
document.head.appendChild(this.styleTag)
}
/* update the styles if the data source has changed */
componentDidUpdate ({ styles: prevStyles }, prevState) {
const { styles: currentStyles } = this.props
if (!isEqual(currentStyles, prevStyles)) {
// generate the css ex
const css = `
.some_selector {
color: ${currentStyles.color}
}
`
// update the <style> node
this.styleTag.textContent = css
}
}
render() {
const { children } = this.props
return children
}
}
你会像这样使用它
<ThemeProvider>
<RootComponent/>
</ThemeProvider>
优点
- 从一个位置全局应用 CSS
- 在和解方面相当便宜
缺点
- 涉及一点“魔法”(即这些样式来自哪里?)
- 组件在应用样式之前安装 - 即渲染之后...这意味着第一次加载可能在 中具有“flash”样式
- 具有轻微破坏性 -
.some_selector { color: ... }
会覆盖hover
等效果...不过,没有什么是您无法轻松修复的。<
关于javascript - 在 React 中执行数据库驱动样式的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45017463/