2017-08-13 34 views
1

我有下面的代碼:爲什麼我不能使用「this」在類組件中使用mystyle?

import React, { Component } from 'react'; 
import { Text, view } from 'react-native'; 

class LoginForm extends Component { 


    render() { 
     return(
     <Text style={ styles.errorMessageStyle }> 
      {this.props.auth.error} 
     </Text> 
    ); 
    } 
} 

const styles = { 
    errorMessageStyle: { 
    fondSize: 20, 
    alignSelf: 'center' 
    } 
}; 

爲什麼當我在style={ this.styles.errorMessageStyle }使用this它讓我錯誤Cannot read property 'errorMessageStyle' of undefind。 但是當我刪除它的作品?

+1

因爲你不明白這是什麼意思。 'this'指向當前實例,但'styles'在您的模塊中聲明爲const,並且不會綁定到任何實例 – Dummy

+0

@Dummy您可以添加更多細節並將其作爲答案發布嗎? – farmcommand2

回答

1

因爲你的風格對象不在你的班級,並且使用this你可以訪問你的班級成員。 如果你想這樣做,你應該在你的類中定義你的樣式對象。

2

this引用當前對象,將被顯式的LoginForm。您的styles變量不是LoginForm一部分,因此不能使用this

class SomeObject extends Component { 
    constructor(props){ 
    super(props) 
    someVariable = "Hello, World" 
    } 

    someOtherMethod() { 
    //... 
    } 


    render() { 
    //... 
    } 
} 

const someStyles = { 

}; 

從上面的例子被調用,則不能使用this到稱爲someStyles,但對於someVariable,它是當前的對象的範圍內,因此this可以使用,someOtherMethod方法同樣適用於對象

+0

爲什麼我的'styles'變量不是'LoginForm' – farmcommand2

+0

@ farmcommand2的一部分,因爲它正在類對象之外聲明。 (不要與具有單個jsx/js文件的類對象混淆 – XPLOT1ON

+0

如果文件中有多個類,則此關鍵字將引用該代碼所在的Class對象 – XPLOT1ON

0

因爲this引用了當前對象。你style聲明應該由:

const styles = { 

this.styles = { 

最後一個必須是你的類中。

現在您可以使用this裏面的style

0

stylesconstant。和points到當前實例。

如果stylesclass返回樣式對象,那麼你也可以使用this.styles()的方法,但在你的情況下,你將它定義爲一個constant

希望這會有所幫助。

相關問題