2017-04-06 3 views
0

私はReact-Nativeを使い慣れていて、他のコンポーネントからメソッドを呼び出そうとしていますが、正しく参照にアクセスできないようです。ここでPostComponentコンポーネントで別のコンポーネントからメソッドを呼び出すための参照にアクセスできない

<Content contentContainerStyle={styles.content}> 
... 
    <PostComponent style={styles.cardStyle} ref="cardRef" /> 
    <View style={styles.horizontalTextContainer}> 
     <this.refs.cardRef.getText /> 
    </View> 
... 
</Content> 

のように見え、ここに私が呼んしようとしている方法だ私は、メソッドのレンダリング方法は次のとおりです。同じコンポーネントのコンストラクタで

getText() { 
    return (
     <Text>Hello</Text> 
    ); 
    } 

、私はちょうど罰金REFを使用することができますそうのようなメソッドを呼び出します。

不思議
constructor(props) { 
    super(props); 
    newthis = this 
    this.state = { 
     time: 20, 
     cards: [], 
    } 
    var timer = setInterval(() => { 
     this.setState({ 
     time: --this.state.time, 
    }) 
    if(this.state.time == 0) { 
     this.setState({ 
      time: 20, 
     }) 
     this.refs.cardRef.timesUp(); 
     } 
    }, 1000); 
    } 

、refは右のそれの外setInvervalメソッドの内部で動作しますが、ではない - どの範囲でも、ここで働いていますか?また、コンポーネントのいくつかのメソッドでは "this"にアクセスできない(定義されていない)ため、これをグローバルに保存するためのハッキリ "newthis"があります。

答えて

0

コンストラクターでは、呼び出しが行われるとコンポーネントはまだマウントされません。 refsは、componentDidMountライフサイクルメソッドの後にのみ安全にアクセスできます。また、文字列型の参照は非難されていますhttps://facebook.github.io/react/docs/refs-and-the-dom.html。コールバック関数の構文を使用してください。

あなたの場合、時間間隔のためにrefはおそらくsetIntervalで動作しています。コンポーネントは1000msでマウントされていました。

そしてハックを避けるために、矢印関数を使用するか、コンストラクタでバインドすることができます。コンポーネントのほとんどのコールバック関数は、独自のコンテキストを持ちます(this)。

constructor(props) { 
    super(props); 
    newthis = this 
    this.state = { 
     time: 20, 
     cards: [], 
    } 
} 
componentDidMount() { 
    this.timer = setInterval(() => { 
     this.setState({ 
     time: --this.state.time, 
    }) 
    if(this.state.time == 0) { 
     this.setState({ 
      time: 20, 
     }) 
     this.cardRef.timesUp(); 
     } 
    }, 1000); 
    } 
    componentWillUnmount() { 
    clearInterval(this.timer) 
    } 
... 

<Content contentContainerStyle={styles.content}> 
... 
    <PostComponent style={styles.cardStyle} ref={(ref) => this.cardRef = ref} /> 
    <View style={styles.horizontalTextContainer}> 
     {this.cardRef.getText()} 
    </View> 
... 
</Content> 
関連する問題