[英]Using conditional imports in React
我是在 React 中构建东西的新手,我正在尝试将一个组件组合在一起,该组件将自行设置样式,但可以选择由调用上下文设置样式。 所以我有这样的事情:
/*eslint-disable*/
import React from "react";
import PropTypes from "prop-types";
import classNames from "classnames";
import styles from "./style.js";
function Section(props) {
const { style } = props;
if (style) import styles from style; // unhappiness here
const classes = styles();
const sectionClasses = classNames({
[classes.section]: true
});
return (
<div className={sectionClasses}>
{props.children}
</div>
)
}
Section.propTypes = {
style: PropTypes.string
}
export default Section
但是,当然, import
不高兴被这样处理(请参阅: 我如何有条件地导入 ES6 模块? )。 我想只使用require()
但我感觉 webpacking 会受到影响
那么这通常是如何实现的呢?
你真的需要有条件的进口吗? 这可能是一个更好的方法:
import styles1 from "./style1.js";
import styles2 from "./style2.js";
// or import { styles1, styles2 } from "./style.js";
...
function Section(props) {
const { style } = props;
let styles;
if (style) styles = style1;
else styles = style2;
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.