[英]Pass a style value from a file to another one in react native
我是React的初學者,我正在嘗試將文件中的樣式值提供給另一個文件。
這是Square.js:
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import Numbers from './Numbers';
export default class Square extends React.Component {
render() {
return (
<View style={squareStyles.square}>
<Numbers number={this.props.squareNumber}></Numbers>
</View>
);
}
}
const squareStyles = StyleSheet.create({
square: {
width: 100,
height: 100,
flex: 1,
backgroundColor: 'skyblue',
borderWidth: 3,
borderColor: 'black',
alignItems: 'center',
justifyContent: 'center',
},
});
這是App.js
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import Square from './Square';
export default class App extends React.Component {
render() {
let flexDirection = StyleSheet.flatten(styles.image).flexDirection;
return (
<View>
<Text style={styles.title}>{flexDirection}</Text>
<View style={styles.imageContainer}>
<Text style={styles.flexboxTitle}>flexbox</Text>
<View style={styles.image}>
<Square squareNumber='1'></Square>
<Square squareNumber='2'></Square>
<Square squareNumber='3'></Square>
</View>
</View>
</View>
);
}
}
function ucFirst(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
const styles = StyleSheet.create({
title: {
alignItems: 'center',
textAlign: 'center',
fontWeight : 'bold',
fontSize: 20,
marginTop: 30
},
imageContainer : {
alignItems: 'center',
marginTop: 30,
marginRight: 20,
marginLeft: 20,
padding: 20,
borderWidth: 4,
borderColor: 'black',
height: 400
},
flexboxTitle : {
marginBottom: 20
},
image : {
flex: 1,
flexDirection : 'row',
height: 800,
paddingTop : 80
}
})
我想從Square.js獲取square backgroundColor的值,並將其導入App.js。
我試圖用StyleSheet.flatten聲明變量,但我真的不知道在哪里聲明它以及如何將其賦給App.js。
謝謝您的幫助。
@ R.Duteil有正確的主意。 在這種情況下,絕對最好將樣式常量保存在單獨的文件中(可能在StyleSheet文件夾下),並根據需要導出/導入。 另外-您提到的問題是您想將Square樣式傳遞給App組件。 對於React來說,通過許多解決方案將道具從孩子傳遞到父母是一個復雜的問題(他們稱其為“提升狀態”)。 關於這個主題,有很多文章可供閱讀,但是對於在組件之間傳遞樣式而言,沒有什么特別有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.