javascript - 找不到模块 : can't resolve 'moduleName' in react js

标签 javascript reactjs

在从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/

相关文章:

javascript - ASP.NET MVC 如何使用 signaturepad 库将签名的 byte[] 转换为保留签名图像的 jpeg?

javascript - 如何隐藏日期时间 x Axis 但仍然能够在 Highcharts 甘特图中显示绘图线?

javascript - Angular queryParams 订阅不触发(选中所有复选框)

reactjs - React js this.props.variable 在子组件中未定义

reactjs - 片段和严格模式有什么区别?

javascript - Response.text() promise 什么时候会拒绝?

javascript - Highstock x 轴日期时间

javascript - 在 ReactJS 迭代中插入 <br/>

reactjs - 访问 React 中的组件方法

reactjs - webpack 生产构建无法正常工作