在从official documentation学习react JS时页面,到目前为止一切正常,现在当我尝试从另一个页面中的另一个页面导出一种方法时,如下所示(每个片段顶部的文件名)
src/Greeting.js
function UserGreeting() {
return <h1>Welcome back!</h1>;
}
function GuestGreeting() {
return <h1>Please sign up.</h1>;
}
function Greeting(props) {
const isLoggedIn = props.isLoggedin;
if(isLoggedIn) {
return <UserGreeting />;
} else {
return <GuestGreeting />;
}
}
export default Greeting;
src/LoginControl.js
import React from 'react';
import Greeting from 'Greeting';
function LoginButton(props) {
return <button onClick={props.onClick}>Login</button>;
}
function LogoutButton(props) {
return <button onClick={props.onClick}>Logout</button>;
}
class LoginControl extends React.Component {
constructor(props) {
super(props);
this.handleLoginClick = this.handleLoginClick.bind(this);
this.handleLogoutClick = this.handleLogoutClick.bind(this);
this.state = {isLoggedIn: false};
}
handleLoginClick() {
this.setState({isLoggedIn: true});
}
handleLogoutClick() {
this.setState({isLoggedIn: false})
}
render() {
const isLoggedIn = this.state.isLoggedIn;
let button = null;
if(isLoggedIn) {
button = <LogoutButton onClick={this.handleLogoutClick} />;
} else {
button = <LoginButton onClick={this.handleLoginClick} />;
}
return (
<div>
<Greeting isLoggedIn={isLoggedIn} />
{button}
</div>
);
}
}
导出默认的LoginControl;
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import LoginControl from './LoginControl';
ReactDOM.render(
<LoginControl />,
document.getElementById('login')
);
ReactDOM.render(<App />, document.getElementById('root'));
public/index.html
<body>
<div id="root"></div>
<div id="login"></div>
</body>
但浏览器中出现以下错误?
./src/LoginControl.js Module not found: Can't resolve 'Greeting' in '/opt/rqt/src'
为什么我会收到此错误?
我需要在 Greeting.js 中创建一个类而不是直接导出函数吗?
最佳答案
您收到该错误是因为您错误地导入了模块。 如果您这样做:
import Greeting from 'Greeting';
您的编译器将在 node_modules
(可能还有其他目录,具体取决于您的配置)中查找该文件。
由于它位于同一目录中,因此您必须将其导入为:
import Greeting from './Greeting';
基本上 ./
表示该文件存在于当前工作目录中。
关于javascript - 找不到模块 : can't resolve 'moduleName' in react js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46664396/