组件基础
组件基础
组件声明
组件样式
样式声明
接下来我们
import { StyleSheet } from "react-native";
// 创建能够用于 React Native 组件的样式表
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "ghostwhite"
},
box: {
width: 100,
height: 100,
justifyContent: "center",
alignItems: "center",
backgroundColor: "lightgray"
},
boxText: {
color: "darkslategray",
fontWeight: "bold"
}
});
export default styles;
在真实项目中随着组件复杂度的增加,我们往往会遵循单一职责原则将组件的样式声明抽取到单独的文件中,然后在组件内引入该样式文件,有点类似于
Flexbox 布局
应用主题设置
CSS-in-JS
font: bold 14px/16px "Helvetica";
margin: 5px 7px 2px;
其对应转换为
{
fontFamily: 'Helvetica',
fontSize: 14,
fontWeight: 'bold',
fontStyle: 'normal',
fontVariant: [],
lineHeight: 16,
marginTop: 5,
marginRight: 7,
marginBottom: 2,
marginLeft: 7,
}
这里为了避免声明复杂的样式类,我们可以选用一些
import transform from 'css-to-react-native';
// or const transform = require('css-to-react-native').default;
transform([
['font', 'bold 14px/16px "Helvetica"'],
['margin', '5px 7px 2px'],
['border-left-width', '5px'],
]); // => { fontFamily: 'Helvetica', ... }
我们也可以转换某个单独的样式属性名或者匹配对象:
import { getPropertyName, getStylesForProperty } from 'css-to-react-native';
getPropertyName('border-width'); // => 'borderWidth'
getStylesForProperty('borderWidth', '1px 0px 2px 0px'); // => { borderTopWidth: 1, ... }
交互事件
在标准的