2016-12-21 13 views
0

私は通知クラスを持っています、通知メッセージはoutsiedeから設定されるものとします。今、this.setStateは定義されていません。これをどうすれば解決できますか?どのようにスタティックリアクション機能で状態を設定できますか?

が反応:

const Notification = React.createClass({ 

    statics: { 
    createAlert: function(message) { 
     this.setState({message: message}); 
    } 
    }, 

    getInitialState: function() { 
    return { 
     message: '', 
    }; 
    }, 
+0

どのようにそのメソッドを呼び出していますか?その可能性は、 'これはあなたが期待するもの以外のものです。 – putvande

+0

私はそれを別の反応クラスから呼び出します。私は実際に通知クラスの "これ"に対処したいと思う – vuvu

+1

私はそれが反パターンだと思う。私はあなたが '小道具 'を設定したいと思いますか? – putvande

答えて

1

静は、インスタンスを持っていません。それは統計の全体点です。つまり、クラス間で共有されているため、thisというコンテキストが動作しません。静的でこれを行うべきではありません。私はES6構文しか使用していないので、構文的に間違っている可能性があります。

const Notification = React.createClass({ 
    setMessage: function(message) { 
     this.setState({message: message}); 
    } 
    getInitialState: function() { 
     return { 
      message: '', 
     }; 
    } 
    render: function() { 
     return (
      //Pass the setMessage function as a prop to a child class 
      //You will need to .bind() setMessage somewhere 
      <ChildClass setMessage={this.setMessage} /> 
     ) 
    } 
}); 

const ChildClass = React.createClass({ 

    doSomething: function() { 
     this.props.setMessage("Hello"); 
    } 
    render: function() { 
     return (

     ) 
    } 
}); 

子クラスが複数のレベルでネストされている場合は、redux、fluxのような状態管理を使用するか、リアクションのコンテキストを使用できます。

関連する問題