My style object: mainModule/styles.js
export default StyleSheet.create({
container: {
width: 0
},
basicInfo: {
height: 167,
backgroundColor: 'red,
justifyContent: 'center',
alignItems: 'center'
}
}
When I importing import generalStyle from '@mainModule/styles'
(I created a package.json
file to make that path works)
And the console log shows like this:
Object { container: 10, basicInfo: 118 }
Could anyone here can help me?
import { StyleSheet } from 'react-native'; export default StyleSheet. create({ container: { padding: 10, alignItems:'center', justifyContent:'center', backgroundColor: '#43a1c9', }, buttonText: { fontSize: 20, textAlign: 'center' } }); This has a few benefits: This makes the component code much cleaner.
In regular React, you will have to use Object. assign() or the spread operator to combine two styles. In React Native, there's a third and better way to combine styles. Use the array operator.
Performance: Making a stylesheet from a style object makes it possible to refer to it by ID instead of creating a new style object every time. It also allows to send the style only once through the bridge.
flatten() Flattens an array of style objects, into one aggregated style object. Alternatively, this method can be used to lookup IDs, returned by StyleSheet. register . NOTE: Exercise caution as abusing this can tax you in terms of optimizations. IDs enable optimizations through the bridge and memory in general.
@NellyNgo, you probably trying to flatten the whole object that StyleSheet.create
returns. I did the same and it was driving me crazy, because it seemed to work for everyone else but for me returned the same value that I've passed to it. Actually flatten will work for the separate property of the object that was created by StyleSheet.create
. Like this:
const styles = StyleSheet.create({prop: {...}, prop2: {...})
and then you can do StyleSheet.flatten(styles.prop)
Check the code in node_modules/react-native/Libraries/StyleSheet/flattenStyle.js. that's the place where it failed for me.
function getStyle(style) {
if (typeof style === 'number') {
return ReactNativePropRegistry.getByID(style);
}
return style;
}
Check the whole source if interested
My RN version is 0.41.2
StyleSheet.create
creates style ids that are cached in order to reduce the amount of data that goes through the bridge.
You can use them and they will work perfectly, but if you need to alter them after importing, you should export the style object without StyleSheet.create
.
In styles.js:
const stylesObj = {
container: {
width: 0
},
basicInfo: {
height: 167,
backgroundColor: 'red',
justifyContent: 'center',
alignItems: 'center'
}
}
export default stylesObj
And in the component:
import stylesObj from 'styles'
const styles = StyleSheet.create(stylesObj)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With