从另一个文件导入ReactJS组件? [英] Import ReactJS component from another file?
问题描述
我是React的新手。想要在单独的文件中使用小组件开发应用程序并将它们导入我的App.js
I'm new to React. Want to develop an app using little components in separate files and import them to my App.js
我试过但是无法弄清楚我做错了什么。
I tried but not be able to figure out what I'm doing wrong.
这是我的HTML:
<!DOCTYPE html>
<html>
<head>
<title>App</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<script src="https://unpkg.com/react@15.3.2/dist/react.js"></script>
<script src="https://unpkg.com/react-dom@15.3.2/dist/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
</head>
<body>
<script type="text/babel" src="js/App.js"></script>
</body>
</html>
这是我的App.js: (来自js /目录)
This is my App.js: (From js/ directory)
import MyComp from 'components/MyComp';
class App extends React.Component {
render() {
return (
<MyComp />
)
}
}
ReactDOM.render(
<App />,
document.body
);
这是我的MyComp.js (来自js / components /目录)
And this is my MyComp.js (From js/components/ directory)
class MyComp extends React.Component{
render() {
return (
<div>
Hello World!
</div>
)
}
}
export default MyComp;
如果我这样试试,我什么也看不见。然而,如果我在App.js中创建 MyComp
类,它就像魅力一样。
If I try this way I see nothing. Whereas if I create MyComp
class in App.js it works like a charm.
任何建议我在做什么错误?
Any suggestion what am I doing wrong?
推荐答案
在大多数情况下,你所拥有的应该是有效的,但我不太确定为什么它没有。我建议在导入位置添加./,但如果这不正确,则会出错并且不会自动消失。
For the most part, what you have should work, but I'm not quite sure why it doesn't. I would recommend adding "./" to the import location, but if that was incorrect, it would error out and not silently go away.
允许我发布一个偶数更简单的版本,我知道确实有效:
Allow me to post an even simpler version which I know does work:
./ index.js:
./index.js :
import React from 'react';
import ReactDOM from 'react-dom';
import Application from './components/Application'
ReactDOM.render(<Application />, document.getElementById('root'));
./ components / Application:
./components/Application :
import React from 'react';
class Application extends React.Component {
render() {
return (
<div className="App">
My Application!
</div>
);
}
}
export default Application;
这应该是使其运作所需的一切。
如果你想进一步缩短上述内容,通过删除底部的 export
行,一种不那么传统的方法就是定义像这样的类...
If you want to shorten the above even more, by removing the export
line at the bottom, a less traditional approach would be defining the class like this...
export default class Application extends React.Component {...}
这篇关于从另一个文件导入ReactJS组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!