2017-09-11 10 views
0

Iちょうどたいここに私のコードだ..私は他のクラスからthis.state.sampleStringにアクセスする方法を尋ねる[リアクトネイティブ]

class MainClass extends Component { 

    constructor(props){ 
     super(props) 


     this.state = { 
     sampleString: 'Test String' 
     } 

     this.getValue = this.getValue.bind(this); 
    } 


    getValue(){ 
     //console.log(this.state.sampleString); 
     return this.state.sampleString 
    } 

} 

======= ==

これは私の第二のクラスから私の機能は、それが「未定義」を返しなぜ

function getValueFromMainClass() { 

    var stringFromClassHeader =() => {HeaderWithBg.getValue()} 

    console.log(stringFromClassHeader.sampleString); 

} 

MainClass

から「this.state。sampleString」の値を取得するのですか?

ありがとう。私は反応したネイティブで新しい。

答えて

1

this.state.sampleStringを支柱として他のコンポーネントに送信して使用することができます。これの簡単な例は次のとおりです。

class MainClass extends Component { 
    constructor(props){ 
     super(props) 
     this.state = { 
     sampleString: 'Test String' 
     } 

     this.getValue = this.getValue.bind(this); 
    } 

    getValue(){ 
     //console.log(this.state.sampleString); 
     return this.state.sampleString 
    } 

    render(){ 
     return (
     <ChildClass sampleString={this.state.sampleString}/> 


     ) 
     } 
    } 

class ChildClass extends Component { 
    somefunction() { 
     //console.log(this.props.sampleString); 
     return this.props.sampleString 
    } 

    render(){ 
     return ... 
    } 
} 
+0

私にサンプルコードを教えてもらえますか?私はネイティブに反応するために新しい..ありがとう! –

+0

答えを更新します。 –

+0

ありがとうございました! :) –

関連する問題