13

http://codepen.io/JessieZhou/pen/VPgMdP,这里有一个在 CodePen 中使用 React 的演示,但是浏览器报错“Uncaught ReferenceError: Component is not defined”。但是,如果我在第一行插入一行“import {Component} from 'react'”,错误将是“Uncaught ReferenceError: require is not defined”。'class'的使用是否有可能导致这个问题?

这是我的代码:

//import {Component} from 'react'
class MyInput extends Component{
   constructor(props){
     super(props);
     this.handleChange = this.handleChange.bind(this);
   }

   handleChange(e){
     this.props.update(e.target.value);
   }

   render(){
     return <input onChange={this.handleChange} type="text"/>
   }
}
ReactDOM.render(MyInput, document.getElementById('myinput'));

这是我在 CodePen 中的 javascript 设置:codepen 中的 javascript 设置

4

7 回答 7

7

原因是 Component 是 React 的一部分,要访问它需要使用 React.Component,如果你直接要使用 Component,那么首先从 导入react,如下所示:

import {Component} from 'react';

用这个:

class MyInput extends React.Component{
    constructor(props){
    super(props);
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e){
    console.log('e', e.target.vaule);
  }
  render(){
    return <input onChange={this.handleChange} type="text"/>
  }
}
ReactDOM.render(<MyInput/>, document.getElementById('myinput'));

检查代码笔

于 2017-02-14T09:13:24.573 回答
3

不使用导入,而是使用解构赋值来获取 React.Component。通过 js 设置将 react 添加到 codepen 后,它会执行脚本,这将使 React 在全局范围内可用,窗口。

const {Component} = React;
class MyInput extends Component{
    //Component code
}
于 2019-11-29T00:52:51.697 回答
2

我注意到在16.2process.env.NODE_ENV js 文件中未定义,如果您从Quick-add导入 CDN 。 解决方案是使用来自 unpkg.com 的开发 react 和 ReactDOM 模块:ReactDOM

//unpkg.com/react/umd/react.development.js
//unpkg.com/react-dom/umd/react-dom.development.js

有一个适用于 React 16.2 的示例:CodePen

于 2018-02-19T03:32:21.677 回答
1

组件是反应的子类。因此,无论是导入它还是使用React.Component 在渲染期间,您必须使用 jsx 都 MyInput行不通。<MyInput/>将工作

class MyInput extends React.Component{
    constructor(props){
    super(props);
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e){
    this.props.update(e.target.value);
  }
  render(){
    return <input onChange={this.handleChange} type="text"/>
  }
}
ReactDOM.render(<MyInput/>, document.getElementById('myinput'));
于 2017-02-14T09:18:05.120 回答
1

你可以做class MyInput extends React.Component或切换到Webpackbin

于 2017-02-14T09:18:32.073 回答
1

现在可以直接从 Node 包导入 ESM 到 Codepen 代码:

import { default as React } from 'https://cdn.skypack.dev/react@15.4.2';
import { default as ReactDOM } from 'https://cdn.skypack.dev/react-dom@15.4.2';
于 2021-05-01T10:53:56.567 回答
0

你必须延长React.Component,而不仅仅是Component

你必须渲染<MyInput />而不是MyInput.

试试这个

class MyInput extends React.Component{
  constructor(props){
    super(props);
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e){
    this.props.update(e.target.value);
  }
  render(){
    return <input onChange={this.handleChange} type="text"/>
  }
}

ReactDOM.render(<MyInput />, document.getElementById('myinput'));
于 2017-02-14T09:27:01.600 回答