【问题标题】:How to fix Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object如何修复元素类型无效:期望字符串(用于内置组件)或类/函数(用于复合组件)但得到:对象
【发布时间】:2019-04-02 14:08:49
【问题描述】:

我正在尝试运行 ReactRails 应用程序并尝试运行一个非常简单的 react-select 组件。但是,在同一个文件中,如果我只打印一个简单的 h2 元素,它可以工作,但 <Select/> 不起作用。它给出了:

Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

我正在尝试使用react-select 组件。我已经通过yarn add 命令安装了它。

User.jsx:

var React = require("react")
var Select = require("react-select")
var PropTypes = require("prop-types")

// also tried these ->
// import React from 'react';
// import createClass from 'create-react-class';
// import PropTypes from 'prop-types';
// import Select from 'react-select';


const options = [
  { value: 'chocolate', label: 'Chocolate' },
  { value: 'strawberry', label: 'Strawberry' },
  { value: 'vanilla', label: 'Vanilla' }
];

class User extends React.Component {
  state = {
    selectedOption: null,
  }
  handleChange = (selectedOption) => {
    this.setState({ selectedOption });
    console.log(`Option selected:`, selectedOption);
  }
  render() {
    const { selectedOption } = this.state;

    /*
    return (
             <h2>THIS WORKS!</h2>
    )
    */



    return (
             <Select
                 value={selectedOption}
                 onChange={this.handleChange}
                 options={options}
             />
    )

    // Doesn't work:
    // Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

  }
}
module.exports = User

我对 React 世界很陌生。我在这里想念什么?我做错了什么?

注意:这并没有解决我的问题:Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object

【问题讨论】:

  • 你为什么把import Select....注释掉了?
  • 我试过import-way 和var Select... 方式。使用importvar 都会出错。如果我使用“导入”,我会得到“元素类型无效:需要一个字符串(对于内置组件)或一个类/函数(对于复合组件)但得到:未定义”(注意未定义的结尾。)
  • 您的导入语法很好(只要您捆绑您的代码)。乍一看,您的其余代码似乎也很好。想也许它在你的应用程序的其他地方?这是一个快速而肮脏的工作示例codesandbox.io/s/zx45kql9q4

标签: reactjs react-select react-rails


【解决方案1】:

我不确定 module.exports 如何与 React 配合使用。当我使用 ES6 语法尝试您的代码时,它似乎工作正常。

import React from 'react';
import Select from 'react-select';

然后使用 ES6 导出而不是 module.exports:

export default User;

Select 组件似乎不是问题。

【讨论】:

  • export default User;!谢谢!。
猜你喜欢
  • 2018-02-19
  • 2021-04-23
  • 2022-08-15
  • 2020-05-09
  • 2021-06-07
  • 1970-01-01
  • 2019-09-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多