2017-08-13 65 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

希望这会有所帮助。

相关问题