我有以下内容:
className={`${this.props.match.params.id}.alert`}
/* desired output = `className="style_alert__3TLGs"` */
/* instead output = `className="style.alert"` */
如果我对className进行硬编码(例如{style.alert}
),则会得到所需的输出。似乎结果是一个字符串,并且没有由css-module包处理(也许是因为它是在之后渲染的?),如何更改此值,以便className由css-module处理并按我的意愿捆绑在一起?
参考文档:css-modules
选项1:导入您将要使用的所有样式模块
创建一个导入的“样式”对象的映射,以id
通过prop中传递的s作为键。只需确保所有“样式”对象具有所有相同的CSS属性,例如“ alert”,当然,请在对象的id
参数路径上使用保护模式,这样就不会进行“ undefined of”访问。
import styles1 from "....";
import styles2 from "....";
...
const stylesMap = {
style1Id: styles1,
style2Id: styles2,
...
};
...
className={stylesMap[this.props.match.params.id].alert}
优点:预先加载您需要的所有CSS模块,并且可能更容易进行推理和调试
缺点:使用更多资源
选项2:使用动态导入
创建一个异步函数来“获取”所需的CSS模块,并使用组件生命周期函数或效果挂钩来更新样式对象引用。
const loadStyle = async (...params) => {
try {
const styleObject = await import(...path and module name from params);
// setState or useState setter to set style object
} catch {
// set a fallback style object
}
}
...
componentDidMount() {
// check props.match.params.id
// gather up other CSS module path details
// trigger dynamic CSS module load
loadStyle(... CSS module path detials);
}
**OR**
useEffect(() => {
// check props.match.params.id
// gather up other CSS module path details
// trigger dynamic CSS module load
loadStyle(... CSS module path detials);
}, [props.match.params.id, ...any other dependencies]);
...
className={stylesMap[<this.>state.styleObject].alert}
优点:体积小/资源占用少。
缺点:由于未提前获取资源,渲染时可能会有更多延迟。
注意:这还取决于您的应用使用情况,需求和要求。例如,如果它是捆绑的应用程序(例如,cordova / phonegap,电子等),那么包含所需的所有资源会更明智。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句