我的项目中有一个样式文件,我在其中定义了一些样式表。现在在我的 App.tsx 中,我导入这些样式表,并将它们传递给我作为 prop 创建的组件。
styles.tsx:
import React from 'react';
import { StyleSheet } from 'react-native';
const style = StyleSheet.create({
t1: {
flex: 1,
alignItems: 'flex-end'
},
t2: {
flex: 1,
alignItems: 'flex-start'
},
});
export style;
组件.tsx:
import React from 'react';
import { Text, View } from 'react-native';
const Component = (props) => {
return (
<View style={props.style1}>
<View style={props.style2}>
<Text>
just a text
</Text>
</View>
</View>
);
};
export default Component;
app.tsx:
import React from 'react';
import Component from './component';
import style from './styles';
const App = () => {
return (
<Component style1={style.t1} style2={style.t2} />
);
};
export default App;
是的,这是可能的。
你走在正确的轨道上。
由于您使用的是 Typescript,因此声明类型很重要。
styles.tsx
import { StyleSheet } from 'react-native';
const styles = StyleSheet.create({
t1: {
flex: 1,
alignItems: 'flex-end'
},
t2: {
flex: 1,
alignItems: 'flex-start'
},
});
export default styles; // Use 'export default' to export the styles object
组件.tsx
import React from 'react';
import { Text, View, ViewStyle } from 'react-native';
interface ComponentProps {
style1: ViewStyle; // Specify the type for style1
style2: ViewStyle; // Specify the type for style2
}
const Component: React.FC<ComponentProps> = (props) => {
return (
<View style={props.style1}>
<View style={props.style2}>
<Text>
just a text
</Text>
</View>
</View>
);
};
export default Component;
app.tsx
import React from 'react';
import Component from './component';
import styles from './styles';
const App = () => {
return (
<Component style1={styles.t1} style2={styles.t2} />
);
};
export default App;