我想要完成的是:我已經創建了基於TouchableOpacity的按鈕組件。在我的應用程序中,我有3種類型的不同外觀的按鈕,它們都共享一些樣式,並具有特定的內容。下面是我Button.js看起來像:我可以通過道具傳遞物品名稱嗎?
import React, { Component } from 'react';
import { Text, TouchableOpacity } from 'react-native';
class Button extends Component {
render() {
const { children, onPress, style } = this.props;
const { buttonStyle, textStyle } = styles;
return (
<TouchableOpacity onPress={onPress} style={[buttonStyle]}>
<Text style={[textStyle]}>
{children}
</Text>
</TouchableOpacity>
);
}
}
//Commonly shared button styles
const styles = {
textStyle: {
alignSelf: 'center',
fontSize: 17,
paddingTop: 15,
paddingBottom: 15
},
buttonStyle: {
alignSelf: 'stretch',
marginLeft: 15,
marginRight: 15
}
};
//Below are specific appearance styles
const black = {
container: {
backgroundColor: '#000'
},
text: {
color: '#FFF'
}
};
const white = {
container: {
backgroundColor: '#FFF'
},
text: {
color: '#000'
}
};
這將是巨大的,如果我可以使用這個按鈕是這樣的:
<Button onPress={} style='black'>PLAY</Button>
<Button onPress={} style='white'>CANCEL</Button>
即默認的buttonStyle和textStyle是從樣式對象中應用的。我只想傳遞一個單詞('黑色','白色')來引用Button組件中描述的其他樣式對象。
我知道我可以用開關創建一個輔助方法,但我認爲有一個更簡單的方法來做到這一點。在那兒?
非常感謝!
你不需要把你的樣式放在一個數組中,如果它只有一個 –
可能這個帖子會幫助你。 http://stackoverflow.com/a/31638988/4361743 – karman
我會製作單獨的組件WhiteButton和BlackButton,基於Button,所以你的Button組件將保持除了它自己以外的任何其他邏輯。即使更好的名字是PrimaryButton和SecondaryButton不要使他們的風格特定的名稱。按鈕組件將提供按鈕的基本功能 - 可以按下它,容器和文本可以以任何方式進行樣式設置。您可以重複使用它來創建更復雜的組件,因爲可以壓制很多東西,但它們看起來可能非常不同。 –