reactjs - 如何修复元素类型无效 : expected a string (for built-in components) or a class/function (for composite components) but got: object

标签 reactjs react-select react-rails

我正在尝试运行 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

最佳答案

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

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

然后使用 ES6 导出而不是 module.exports:
export default User;

Select 组件似乎不是问题。

关于reactjs - 如何修复元素类型无效 : expected a string (for built-in components) or a class/function (for composite components) but got: object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53048965/

相关文章:

node.js - 如何使用mocha、node和selenium集成测试react-select多选下拉菜单?

reactjs - 如何使 react 选择下拉菜单中的选项可访问?

javascript - React-Rails - 入门问题

reactjs - React、TypeScript 和 RxJS 测试与 Jest 不工作

javascript - 处理两个完全独立的 React 组件之间的数据

javascript - 如何使用搜索框中的搜索词从 ReactJS 中的多个 URL 获取 JSON 数据?

javascript - react : Generate all date of birth select options

heroku - 使用带有react-rails gem的组件时没有这样的文件或目录@ rb_sysopen

javascript - 基本 React 示例错误 : Uncaught TypeError: undefined is not a function

javascript - 如何将文件图像转换为 Byte[] ReactJS?