我制作了一个自定义组件,希望在其中传递不同的边距和字体大小,因此我将它们作为概率传递。当我将样式放在另一个文件中时出现了问题。
CustomButton.js:
import React from 'react';
import { Text, TouchableNativeFeedback, View, StyleSheet } from 'react-native';
import styles from './Styles';
const CustomButton = ({ onPress, children, marginSize, customFontSize, disabled }) => {
const { buttonStyle, textStyle } = styles;
return (
<TouchableNativeFeedback onPress={onPress} disabled={disabled}>
<View style={buttonStyle}>
<Text style={textStyle}>
{children}
</Text>
</View>
</TouchableNativeFeedback>
);
};
export default CustomButton;
Styles.js:
import { StyleSheet } from 'react-native';
export default StyleSheet.create({
buttonStyle: {
backgroundColor: '#38A1F3',
borderRadius: 30,
borderWidth: 1,
borderColor: '#38A1F3',
marginLeft: 5,
marginRight: 5,
},
textStyle: {
color: '#FFFF',
fontSize: customFontSize,
fontWeight: 'bold',
paddingTop: 3,
paddingBottom: 3,
marginLeft: marginSize,
marginRight: marginSize,
textAlign: 'center',
},
});
我知道它不会以这种方式工作,因为marginSize
和customFontSize
在Styles.js文件的任何地方都没有定义,但是我似乎找不到解决方法
答案 0 :(得分:0)
您可以传播从styles.js文件导入的样式,然后添加所需的属性。
import React from 'react';
import { Text, TouchableNativeFeedback, View, StyleSheet } from 'react-native';
import styles from './Styles';
const CustomButton = ({ onPress, children, marginSize, customFontSize, disabled }) => {
const { buttonStyle, textStyle } = styles;
return (
<TouchableNativeFeedback onPress={onPress} disabled={disabled}>
<View style={buttonStyle}>
<Text
style={{
...textStyle,
marginLeft: marginSize,
marginRight:marginSize,
fontSize: customFontSize}}
>
{children}
</Text>
</View>
</TouchableNativeFeedback>
);
};
export default CustomButton;
答案 1 :(得分:0)
选项1 根据您要实现的目标,可以使textStyle
成为一个功能
textStyle: (fontSize, marginHorizontal) => ({
color: '#FFFF',
fontSize,
fontWeight: 'bold',
paddingTop: 3,
paddingBottom: 3,
marginHorizontal,
// if marginLeft and marginRight is always same, you can use marginHorizontal
// (paddingTop and paddingBottom above can be paddingVertical too)
textAlign: 'center',
}),
//and then set your style like this
<Text style={textStyle(customFontSize, marginSize)}>
{children}
</Text>
选项2 在Styles.js
中设置默认值,然后将其替换为CustomButton.js
<Text style={[textStyle, {fontSize: customFontSize, marginHorizontal: marginSize}]}>
{children}
</Text>