2016-08-17 90 views
0

我是ReactJS的新手,我正在基於ES2015學習它。大多數例子都是ES5。我的問題似乎是渲染子組件。ReactJS ES2015兒童組件

我的子組件是一個文本字段

import React, {Component} from 'react'; 

class TextField extends Component { 
    constructor(props, context){ 
    super(props, context); 
    this.state = { 
     customer: { 
     custno: props.customer.custno 
     } 
    }; 
    } 

    render() { 
     if(this.props.displayMode) { 
     return <span>{this.props.custno}</span> 
     } 
     return <input type="text" {...this.props} /> 
    } 
} 

export default TextField; 

我父組件被稱爲AddressBox和將包含許多子控件。如果displayMode爲true,那麼它應該呈現一個SPAN,但如果它是false,它應該呈現一個表單控件。

地址框代碼是:

import React, {Component} from 'react'; 
import {TextField} from '../textfield/textfield.js'; 

class AddressBox extends Component { 
    constructor(props, context){ 
    super(props, context); 
    this.state = { 
     customer: { 
     custno: "" 
     } 
    }; 
    this.onCustomerNumberChange = this.onCustomerNumberChange.bind(this); 
    } 

    onCustomerNumberChange(event) { 
    const customer = this.state.customer; 
    customer.custnumber = event.target.value; 
    this.setState({customer: customer}); 
    } 

    render() { 
     return (
     <div className="addressbox"> 
      <h1>Address Box</h1> 
      <label>Customer Number:</label> 
      <TextField value={this.state.customer.custno} onChange={this.onCustomerNumberChange} /> 
     </div> 
    ); 
    } 
} 

AddressBox.defaultProps= { 
    customer: { 
    name: "", 
    custnumber: "" 
    } 
} 

export default AddressBox; 

當我嘗試呈現這些控件,我得到以下錯誤:

Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components). Check the render method of AddressBox .

Uncaught Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. Check the render method of AddressBox .

所有的例子我能找到使用以前的陣營.createClass方法。誰能告訴我爲什麼TextField會拋出一個錯誤?

回答

1

我想通了,我使用了錯誤的導入語法。

我用

import {TextField} from '../textfield/textfield'; 

時,我應該用:

import TextField from '../textfield/textfield';