问题
Hello there I'm new to react native. I'm trying to create reusable component, not only card component, maybe in future will create other reusable components. Below is the code example of reusable card component that I've created:
Card.js
import React from 'react';
import { View, StyleSheet } from 'react-native';
const Card = props => {
return (
<View style={{...styles.card, ...props.style}}>{props.children}</View>);};
const styles = StyleSheet.create({
card: {
shadowColor: 'black',
shadowOffset: { width: 0, height: 2 },
shadowRadius: 6,
shadowOpacity: 0.26,
elevation: 8,
backgroundColor: 'white',
padding: 20,
borderRadius: 10,
}
});
export default Card;
StartGameScreen.js
import React from 'react';
import { View, Text, StyleSheet, TextInput, Button } from 'react-native';
import Card from '../components/Card';
const StartGameScreen = props => {
return (
<View style={styles.screen}>
<Text style={styles.title}>Start a New Game!</Text>
<Card style={styles.inputContainer}>
<Text>Select a Number</Text>
<TextInput />
<View style={styles.buttonContainer}>
<View style={styles.button}><Button title="Reset" onPress={() => {}} /></View>
<View style={styles.button}><Button title="Confirm" onPress={() => {}} /></View>
</View>
</Card>
</View>
);
};
const styles = StyleSheet.create({
screen: {
flex: 1,
padding: 10,
alignItems: 'center'
},
title: {
fontSize: 20,
marginVertical: 10
},
inputContainer: {
width: 300,
maxWidth: '80%',
alignItems: 'center'
},
buttonContainer: {
flexDirection: 'row',
width: '100%',
justifyContent: 'space-between',
paddingHorizontal: 15
},
button: {
width:100
}
});
export default StartGameScreen;
The Result as below:
I'm expecting it to be as below:
Is it possible to use my above code and have the expected result? or is my code wrong and there is better solution??
回答1:
Your card component is reusable only mistake is the way you are merging the styles. When you merge styles you should not expand it but use an array of styles. Like below.
const Card = props => {
return (<View style={[styles.card, props.style]}>{props.children}</View>);
};
You can check the below snack for full code. https://snack.expo.io/@guruparan/e368b9
来源:https://stackoverflow.com/questions/61758279/react-native-reusable-card-component-wont-visualize-as-expected