2017-05-01 6 views
1

私はReactjsで新規です。私は非常に単純なことをやろうとしています:ユーザがテキスト領域内のテキストを変更すると、レンダー関数内のdivを更新します。助言がありますか?エラー取得未定義のプロパティ 'setState'を読み取ることができません

class HTMLEditor extends React.Component { 
 
    
 
    constructor(props) { 
 
    super(props); 
 
    this.state = {value: 'Put here HTML'}; 
 
    } 
 
    
 
    
 
    handleChange(e) { 
 
    this.setState({value: e.currentTarget.value}); 
 
    } 
 
    
 
    
 
    render() { 
 
    return (
 
     <div> 
 
     <textarea defaultValue={this.state.value} onChange={ this.handleChange } /> 
 
     <div>{this.state.value}</div> 
 
     </div> 
 
    ); 
 
    } 
 
} 
 

 
ReactDOM.render(
 
    <HTMLEditor />, 
 
    document.getElementById('container') 
 
);

+1

にこの答えを参照してください。コンストラクタで 'this.handleChange = this.handleChange.bind(this)'を追加してください – QoP

答えて

1

あなたはhandleChange機能をバインドする必要があります。 handleChange関数this keyworkがReact Classのコンテキストを参照していないため、関数をバインドする必要があるため、このエラーが発生しています。

は、あなただけのコンポーネントに `handleChange`をバインドする必要がwhy do you need to bind event handlers in React

class HTMLEditor extends React.Component { 
 
    
 
    constructor(props) { 
 
    super(props); 
 
    this.state = {value: 'Put here HTML'}; 
 
    } 
 
    
 
    
 
    handleChange = (e) =>{ 
 
    this.setState({value: e.currentTarget.value}); 
 
    } 
 
    
 
    
 
    render() { 
 
    return (
 
     <div> 
 
     <textarea defaultValue={this.state.value} onChange={ this.handleChange } /> 
 
     <div>{this.state.value}</div> 
 
     </div> 
 
    ); 
 
    } 
 
} 
 

 
ReactDOM.render(
 
    <HTMLEditor />, 
 
    document.getElementById('container') 
 
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 
<div id="container"></div>

+0

皆さん、ありがとうございます! this.handleChange = this.handleChange.bind(this)vs arrow関数の違いとベストプラクティスとしての良い点について教えてください。 ありがとう –

+0

この回答を確認http://stackoverflow.com/questions/40760646/bind-in-constructor-or-fat-arrow-in-class –

関連する問題