如何从样式表中引用组件? -React Native



全新的 React Native。我正在玩我在这里找到的零食。以下是我所拥有的:

import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';
export default class LotsOfStyles extends Component {
constructor(props){
super(props)
this.myColor = 'blue'
this.state = {myColor: 'red')
}
render() {
return (
<View>
<Text style={styles.myStyle}>Lorem Ipsum</Text>
</View>
);
}
}
const styles = StyleSheet.create({
myStyle: {
color: this.myColor,
fontWeight: 'bold',
fontSize: 30,
},
});

上面的代码不会崩溃;事实上,它按预期输出"Lorem Ipsum"。但是,文本的颜色不是蓝色 - 它是黑色的,表示样式表的颜色未正确读取。

现在我对RN的了解非常简陋,但是如果我的理解是正确的,那么RN中的this与其他语言的范围非常不同。同样,进一步假设我的理解是正确的,this在上面的例子中指的是styles,因此在类中看不到myColor道具。

所以我的问题是:你如何引用实际的类?

或者引用样式表中的类被认为是不好的做法,应该完全避免?(如果是这样的话,什么是"好"做法?

谢谢

如果您有预定义的颜色,请在常量中使用它 如果要更改某些事件的颜色,请在状态变量

中维护它示例代码:

import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';
const myColor = 'blue'
export default class LotsOfStyles extends Component {
constructor(props) {
super(props);
this.state = ({ color: 'red' })
}
render() {
return (
<View>
<Text style={styles.myStyle}>Lorem Ipsum</Text>
<Text style={[styles.myStyle, { color: this.state.color }]}>Lorem Ipsum</Text>
</View>
);
}
}
const styles = StyleSheet.create({
myStyle: {
color: myColor,
fontWeight: 'bold',
fontSize: 30,
},
});

如果您不想更新颜色,请设置为常量...

const colorBlue = 'blue'

如果您在多个位置使用此颜色,请创建一个类 Color.js并像这样编写此代码

export default {
blue: 'blue',
black: 'black'
}

你想在哪个类中使用它,只需导入颜色类并像这样设置颜色

const styles = StyleSheet.create({
myStyle: {
color: Color.blue,
fontWeight: 'bold',
fontSize: 30,
},
});

如果您在运行时更改颜色,请在状态上设置颜色

constructor(props) {
super(props);
this.state = ({ color: 'red' })
}
const styles = StyleSheet.create({
myStyle: {
color: this.state.color,
fontWeight: 'bold',
fontSize: 30,
},
});

最新更新