gpt4 book ai didi

javascript - ReactJS ES2015 子组件

转载 作者:行者123 更新时间:2023-11-27 22:37:19 26 4
gpt4 key购买 nike

我是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;

当我尝试渲染这些控件时,出现以下错误:

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.

我能找到的所有示例都使用之前的 React.createClass 方法。谁能告诉我为什么 TextField 会抛出错误?

最佳答案

我发现我使用了错误的导入语法。

我正在使用

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

当我应该使用时:

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

关于javascript - ReactJS ES2015 子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39003227/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com