【发布时间】:2016-12-24 12:01:06
【问题描述】:
我是 ReactJS 的新手,我正在基于 ES2015 学习它。大多数例子是 ES5。我的问题似乎是渲染子组件。
我的子组件是一个 TextField
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;
当我尝试渲染这些控件时,我收到以下错误:
警告:React.createElement:类型不应为 null、未定义、 布尔值或数字。它应该是一个字符串(对于 DOM 元素)或 ReactClass(用于复合组件)。检查渲染方法
AddressBox.未捕获的不变违规:元素类型无效:预期为 字符串(用于内置组件)或类/函数(用于复合 组件)但得到:未定义。检查渲染方法
AddressBox.
我能找到的所有示例都使用了之前的 React.createClass 方法。谁能告诉我为什么 TextField 会抛出错误?
【问题讨论】:
标签: javascript reactjs ecmascript-6