In my Card.js I have this code:
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
}
});
And heres the other component:
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}>
<Button title="Reset" onPress={() => {}} />
<Button title="Confirm" onPress={() => {}} />
</View>
</Card>
</View>
);
};
const styles = StyleSheet.create({
inputContainer: {
width: 300,
maxWidth: '80%',
alignItems: 'center'
}
});
export default StartGameScreen;
When I debug my app JSX I wrote in Card.js doesnt apply. Does anyone know how to fix this? It shows no errors at but it still wont apply style property I wrote in Card.js?
CodePudding user response:
Found solution.
<View style={[styles.card, props.style]}>{props.children}</View>
CodePudding user response:
The reason why the construct
{{...styles.X, ...styles.Y}}
is not working in react-native is because the StyleSheet.create()
function is not returning a plain JS object. Thus, we can not apply the spread
operator here.
Indeed, notice that the following will work.
// or whatever style objects
{{...{margin: 10}, ...{backgroundColor: "red"}}}
Since we are passing the styles as plain JS objects.
However, as you have noticed yourself, the usual way to combine multiple styles from a stylesheet inline is using an array.
{[styles.X, styles.Y]}