2017-10-10 75 views
0

雖然學習反應JS從official documentation頁面,一切工作正常,現在,當我試圖從另一個頁面中的另一個頁面導出一個方法如下(文件命名每個片斷的頂部)Module not found:無法解析'moduleName'的反應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')); 

公共/ index.html的

<body> 
    <div id="root"></div> 
    <div id="login"></div> 
</body> 

,但它在瀏覽器中,給出以下的錯誤?

./src/LoginControl.js模塊找不到:無法解析在 '/選擇/ RQT/src目錄'

爲什麼會出現這個錯誤 '問候'?

我是否需要在Greeting.js中創建類而不是直接導出函數?

回答

1

您正在收到該錯誤,因爲您錯誤地導入了模塊。 如果你這樣做:

import Greeting from 'Greeting'; 

你的編譯器會在文件中node_modules(可能還有其他目錄,這取決於您的配置)。


因爲它是在同一目錄下,你必須導入爲:

import Greeting from './Greeting'; 

基本上./意味着該文件存在於當前的工作目錄。

+0

謝謝,但'進口'不考慮默認目錄相同的地方被稱爲? –

+0

@ pro.mean看到我更新的答案。 – Chris

+0

工作正常後,我'添加'反應,{組件}從'反應';'* Greeting.js *頂部與您的建議。但是,我們在Greeting.js中的所有地方都使用了React?爲什麼它需要? –