[英]How To Pass Style Props into a reusable component in React Native for more flexible styling in the future
The Goal: To create a reusable react component and have the flexibility to style any part of the component in the future.目标:创建一个可重用的 React 组件,并在未来灵活地为组件的任何部分设置样式。
for example, I create a button-like component that I want to reuse in different cases in the future and give it different styles in the different places that I use it:例如,我创建了一个类似按钮的组件,我想在未来的不同情况下重用它,并在我使用它的不同地方赋予它不同的样式:
function reusableButton(){
return(
<View style={styles.defaultStyle}>
<Text style={styles.defaultTitleStyle}>Button Title</Text>
</View>
)}
const styles = StyleSheet.create({
defaultStyle:{
height: 50,
width: 100,
borderRadious: 25,
backgroundColor:'red'},
defaultTitleStyle: {
color:'green',
fontWeight: 'bold'}
})
Question is: How do I make changes to the default styles in the future when I use this button?问题是:当我使用这个按钮时,将来如何更改默认样式?
The Goal: To create a reusable react component and have the flexibility to style any part of the component in the future.目标:创建一个可重用的 React 组件,并在未来灵活地为组件的任何部分设置样式。
How to achieve this:如何实现这一点:
Example: Creating the reusable components:示例:创建可重用组件:
const ReusableButton = (props) =>{
return(
<View style={[styles.currentButtonStyle, props.futureButtonStyle]}>
<Text style={[styles.currentButtonTitle, props.futureTitleStyle]}>{props.title}</Text>
</View> )};
//Here are my default styles:
const styles = Stylesheet.create({
currentButtonStyle: {
height:50,
width: 100,
backgrroundColor:'red'},
currentButtonTitle:{
color: 'white'
fontSize: 20,
},
})
Henceforth, anywhere I wish to call and use the ReusableButton, it can edit the styles with the future styles.从此以后,在我希望调用和使用 ReusableButton 的任何地方,它都可以使用未来的样式编辑样式。 Example:例子:
function NewComponent(){
return(
<View>
<Text>Hi let us make use of our old reusable button</Text>
<ReusableButton futureButtonStyle={{width: 200, height: 100, backgroundColor:'blue'}} futureTitleStyle={{fontWeight:'bold', fontSize: 50}}/>
</View>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.