我正在尝试构建react共享ui组件库,并将其作为依赖项添加到另一个react项目(通过create-react-app创建)中。但是,尝试导入Button组件时出现错误。阅读类似的问题,似乎与导入或导出的方式有关,但仍无法解决。
使用共享组件的应用程序出现错误:
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
// App.js
import React from "react";
import { Button } from "my-component-ui-library";
import "./App.css";
function App() {
return (
<div className="App">
<Button>Hello World!</Button>
</div>
);
}
export default App;
共享组件库中的文件夹结构(省略了其他不相关的文件)
.
├── src
│ ├── components
│ │ └── Button
│ │ ├── Button.js
│ │ └── index.js
│ └── index.js
├── .babelrc
└── webpack.config.js
代码
// src/components/Button/Button.js
import React from "react";
import PropTypes from "prop-types";
const Button = ({ children, bg }) => (
<button
style={{
padding: "10px 20px",
border: "none",
color: "white",
fontSize: "16px",
background: bg
}}
>
{children}
</button>
);
Button.propTypes = {
children: PropTypes.node.isRequired,
bg: PropTypes.string
};
Button.defaultProps = {
bg: "#24a7fd"
};
export default Button;
// src/components/Button/index.js
import Button from "./Button";
export default Button;
// src/components/index.js
export { default as Button } from "./Button";
//.babelrc
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ["@babel/preset-env", "@babel/react"]
}
}
}
]
}
};
// package.json
{
"name": "my-component-ui-library",
"version": "1.0.0",
"description": "",
"main": "dist/main.js",
"scripts": {
"build": "webpack",
"prepare": "npm run build"
}
}
答案 0 :(得分:0)
在使用带有默认关键字的export时,导入文件将使您得到一个变量。
例如:
import Button from "my-component-ui-library";
您的代码
import { Button } from "my-component-ui-library";
在从文件导出多个组件并且可以直接将多个组件作为
导入时起作用import { Button, XYZ } from "my-component-ui-library";