2016-12-29 78 views
2

我試圖捕捉的onChange事件的輸入,並呼籲的setState新值,但此後只要我在輸入型我得到:React.js - 「本」甚至不確定結合

Uncaught TypeError: Cannot read property 'setState' of undefined 

即使我已經叫

this.handleChange.bind(this) 
在構造

index.js

import React from 'react' 
import * as ReactDOM from "react-dom"; 
import App from './App' 

ReactDOM.render(
    <App />, 
    document.getElementById('root') 
); 

App.js

import * as React from "react"; 
export default class App extends React.Component { 
    constructor(props) { 
     super(props) 
     this.handleChange.bind(this) 
     this.state = {contents: 'initialContent'} 
    } 


    handleChange(event) { 
     this.setState({contents: event.target.value}) 
    } 


    render() { 
     return (
      <div> 
       Contents = {this.state.contents} 
       <input type="text" onChange={this.handleChange}/> 
      </div> 
     ); 
    } 
} 

回答

7

分配this.handleChange.bind(this)綁定 - 返回新的參考起作用)至this.handleChange,因爲this.handleChange不得不提及新函數返回.bind

constructor(props) { 
    super(props) 
    this.handleChange = this.handleChange.bind(this) 
    this.state = {contents: 'initialContent'} 
}