2017-02-14 53 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'));