[英]Using conditional imports in React
I'm new to building stuff in React and am trying to put together a component that will style itself but that can optionally be styled by the calling context.我是在 React 中构建东西的新手,我正在尝试将一个组件组合在一起,该组件将自行设置样式,但可以选择由调用上下文设置样式。 So I have something like this:
所以我有这样的事情:
/*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
but, of course, import
isn't happy being manhandled like that (see: How can I conditionally import an ES6 module? ).但是,当然,
import
不高兴被这样处理(请参阅: 我如何有条件地导入 ES6 模块? )。 I would like to just use require()
but I have a feeling the webpacking will suffer我想只使用
require()
但我感觉 webpacking 会受到影响
so how is this typically implemented?那么这通常是如何实现的呢?
Do you really need conditional imports?你真的需要有条件的进口吗? This might be a better approach:
这可能是一个更好的方法:
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.