【问题标题】:Importing React Components with ES6使用 ES6 导入 React 组件
【发布时间】:2017-12-13 14:22:30
【问题描述】:

我在 login.js 中有一个 react 组件,我将其保存在一个单独的文件中,然后在我的主文件 App.js 中导入 login.js。我在导入时遇到问题,因为我正在渲染应用程序的本地主机页面只是显示为完全空白,没有给出错误。不知道我做错了什么,我的组件 login.js 的代码如下:

import React, {Component} from 'react';
import * as firebase from 'firebase';


class login extends Component{

constructor(props) {
    super(props)
    this.state = {emailText: '',
                  passwordText: ''
                 }
}


onChangeEmail(e) {
    this.setState({emailText: e.target.value})
}

onChangePassword(e) {
    this.setState({passwordText: e.target.value})
}

signUpUser(){
    console.log(this.state.emailText)
    console.log(this.state.passwordText)

    firebase.auth().createUserWithEmailAndPassword(this.state.emailText, this.state.passwordText)
    console.log('New account created, and is now signed in.')
}

loginUser(){
    console.log('logging in rn')
    firebase.auth().signInWithEmailAndPassword(this.state.emailText, this.state.passwordText)
    console.log('Successfully logged in')
}

logoutUser(){
    firebase.auth().signOut()
    console.log('logged out')
}

    render(){
        return  (
            <div class="container">
            <input onChange={this.onChangeEmail.bind(this)} id="txtEmail" type="email" placeholder="Email"/>

            <input onChange={this.onChangePassword.bind(this)} id="txtPassword" type="password" placeholder="Password"></input>       

            <button onClick={this.loginUser.bind(this)} id="btnLogin" class="btn btn-action">
            Log in </button>    

            <button onClick={this.signUpUser.bind(this)} id="btnSignUp" class="btn btn-secondary">
            Sign Up </button>

            <button onClick={this.logoutUser.bind(this)} id="btnLogout" class="btn btn-action hide">Log Out</button>
        </div>  
        )

    }

};

export default login;

我将 login.js 导入的代码如下:

import React, {Component} from 'react';
import * as firebase from 'firebase'; // Import Firebase library
import login from './login.js';

export default class App extends React.Component {
   render() {
      return (
         <div>
            <login/>
         </div>
      );
   }
}

我的 index.js 如下:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();

【问题讨论】:

  • login 更改为 Login 看看会发生什么。相关info.

标签: reactjs import components


【解决方案1】:

您需要更改login 组件的名称。它需要是Login 而不是login

当它被命名为 Login 并且一切正常时,情况如下:

https://codesandbox.io/s/EkEJ02zY

尝试将其从Login 更改为login,您将得到空白屏幕。

希望这会有所帮助。

【讨论】:

  • 修复了!我所做的只是将组件的名称更改为大写,而在我的 App.js 中缺少一个分号。 2 小时花得值哈哈
猜你喜欢
  • 2016-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-10
  • 2017-08-27
  • 2017-06-23
  • 1970-01-01
  • 2018-06-13
相关资源
最近更新 更多