ClassName 样式在反应中不起作用 [英] ClassName styles not working in react
问题描述
我对 React 组件的样式设置有点问题.我将 scss 样式表放在一个单独的文件中,并将它们导入到我的 react 文件中.我的 scss 样式表如下所示:
.testStyle {字体系列:avenir;颜色:蓝色;}
我的 react 文件是这样的:
从 'react' 导入 React从'../styles/main.scss' 导入样式类 Temp 扩展 React.Component {使成为() {返回 (****<h1>你好</h1>)}}导出默认温度
使用此设置,我的样式不会通过,但是,如果我将带星号的行替换为 <div className='testStyle'>
,那么它看起来像样式正在正确导入.有人能帮忙吗?谢谢.
我假设您在 webpack 中使用了 css 加载器.您需要启用模块:true
<代码>{加载器:'css-加载器',选项: {模块:真}}
如果您不希望此行为成为默认行为,则可以在您的 (s)css 中使用:
//sCSS:local .yourClass {...}//JS从 '../yourCss.scss' 导入 clsconst 组件 = () =>(<div className={cls.yourClass}/>)//yourClass 会变成一些随机散列//或其他基于你的 css 加载器配置的东西
进行处理.如果你有 modules: true 并且你不想让 css loader 编译你的类,你可以使用
//CSS:global .yourGlobalClass {...}//JS导入'../yourCss.scss'const 组件 = () =>(<div className="yourGlobalClass"/>)
查看文档:https://github.com/webpack-contrib/css-loader 和 https://github.com/css-modules/css-modules
I'm having a little issue with styling react components. I have my scss stylesheets in a separate file and importing them into my react file. My scss stylsheet looks like this:
.testStyle {
font-family: avenir;
color: blue;
}
My react file, looks like this:
import React from 'react'
import styles from '../styles/main.scss'
class Temp extends React.Component {
render() {
return (
**<div className={styles.testStyle}>**
<h1>Hello</h1>
</div>
)
}
}
export default Temp
With this setup, my styles are not passed through, however, if it works if I replace the starred line with <div className='testStyle'>
, so it seems like the styles are being imported correctly. Can anyone help with this? Thanks.
I assume you are using css loader in your webpack. You need to enable modules:true
{
loader: 'css-loader',
options: {
modules: true
}
}
If you don't want this behaviour to be default, in your (s)css you can use:
// sCSS
:local .yourClass {...}
// JS
import cls from '../yourCss.scss'
const Component = () => (
<div className={cls.yourClass} />
)
// yourClass will become some random hash
// or something else based on your css loader config
to have it processed. If you have modules: true and you don't want css loader to compile your class, you can use
// CSS
:global .yourGlobalClass {...}
// JS
import '../yourCss.scss'
const Component = () => (
<div className="yourGlobalClass" />
)
See the documentation: https://github.com/webpack-contrib/css-loader and https://github.com/css-modules/css-modules
这篇关于ClassName 样式在反应中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!