2017-02-14 81 views
2

http://codepen.io/JessieZhou/pen/VPgMdP,下面是一个使用作出反应CodePen演示,但是浏览器提供了一个错误“未捕获的ReferenceError:组件没有定义”。但是,如果我在第一行插入一行“从'react'”导入{Component},则错误将为“Uncaught ReferenceError:require is not defined”。 'class'的使用是否有可能导致这个问题?如何Codepen使用与反应器ES6

这里是我的代码:

//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设置: javascript settings in codepen

回答

4

原因是组件是阵营的一部分,你需要使用React.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

+0

非常感谢您!使用React.Component的工作,但如果我想使用组件,“进口{}组件从‘反应’”仍然没有工作,错误的是“未捕获的ReferenceError:要求没有定义” ...... – JessieZhou

+0

使用这条线你的项目,它会工作,我们曾经使用lib链接的codepen,这就是为什么我们必须使用完整的React.Component。 –

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

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

+0

非常感谢〜稍后我会试用Webpackbin〜 – JessieZhou

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