如何在Codepen中使用ES6写React代码

14

http://codepen.io/JessieZhou/pen/VPgMdP,这里是一个在CodePen中使用React的演示,但浏览器会报错“未捕获的引用错误:Component未定义”。然而,如果我在第一行插入一行“import {Component} from 'react'”,则错误将变为“未捕获的引用错误:要求未定义”。是否可能是'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 设置

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'));

查看 codepen


1
非常感谢!使用React.Component会起作用,但如果我想使用Component,“import {Component} from 'react'”仍然无法工作,错误是“Uncaught ReferenceError:require未定义”... - JessieZhou
在你的项目中使用这行代码,它会起作用。在CodePen中,我们通常使用库链接,这就是为什么我们必须使用完整的React.Component的原因。 - Mayank Shukla
Omit the import line - Gorky
这是无用的。它不能解决“require未定义”错误。 - Thomas Levesque

4

不要使用import,而是使用解构赋值来获取React.Component。通过js设置将React添加到Codepen后,它执行的脚本将使React在全局范围内window上可用。

const {Component} = React;
class MyInput extends Component{
    //Component code
}

这应该是被接受的答案。 - Thomas Levesque

2

2
现在可以直接从Node包向Codepen代码进行ESM导入。
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';

1

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


非常感谢您,我稍后会尝试使用Webpackbin。 - JessieZhou

1

组件是react的子类。因此,您可以导入它或使用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'));

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'));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接