flexDirection
含义:flex排列方式
语法:flexDirection:'column'可选属性:column、row、column-reverse、row-reverse
flexGrow和flex的比较
区别:flexGrow是等分父级剩余空间,flex是等份父级全部空间(即width或height不生效)
注意: View无默认100%,必须设置才行
语法:
import React from 'react';
import {View, StyleSheet} from 'react-native';
export default () => {
return (
<View style={styles.root}>
<View style={{flexDirection: 'row', width: '100%'}}>
<View style={[styles.subView, styles.subView1]} />
<View style={[styles.subView, styles.subView2]} />
<View style={[styles.subView, styles.subView3]} />
</View>
<View style={{flexDirection: 'row', width: '100%'}}>
<View style={[styles.subView, styles.subView4]} />
<View style={[styles.subView, styles.subView5]} />
<View style={[styles.subView, styles.subView6]} />
</View>
</View>
);
};
const styles = StyleSheet.create({
root: {
flexDirection: 'column',
height: '100%',
width: '100%',
backgroundColor: '#c0c0c0',
},
subView: {
width: 100,
height: 100,
marginBottom: 10,
},
subView1: {
backgroundColor: 'red',
flexGrow: 1,
},
subView2: {
backgroundColor: 'blue',
flexGrow: 2,
},
subView3: {
backgroundColor: 'pink',
flexGrow: 3,
},
subView4: {
backgroundColor: 'red',
flex: 1,
},
subView5: {
backgroundColor: 'blue',
flex: 2,
},
subView6: {
backgroundColor: 'pink',
flex: 3,
},
});
尺寸属性纯数值和百分比
可设置百分比的属性:
- width、height
- margin相关
- padding相关
position:absolute绝对定位下仍然受父级属性影响
当组件设置了position:absolute但是未设置left或top时,父组件设置了alignItems或justifyContent对齐方式,组件引用父布局
export default () => {
return (
<View style={styles.root}>
<View style={styles.subView} />
</View>
);
};
const styles = StyleSheet.create({
root: {
flexDirection: 'column',
height: '100%',
width: '100%',
backgroundColor: '#c0c0c0',
alignItems: 'center',
justifyContent: 'center',
},
subView: {
width: 100,
height: 100,
marginBottom: 10,
backgroundColor: 'red',
position: 'absolute',
left: 10,
},
});
onLayout
onLayout:给组件绑定这个事件,返回在父布局的位置
什么时候使用:比如滚动东西,当一个达到一个阈值的时候改变布局或样式
<View
style={styles.subView}
onLayout={e => {
console.log(e.nativeEvent);
}}
/>
setNativeProps:命令式更新
const viewRef = useRef(null);
useEffect(() => {
setTimeout(() => {
viewRef?.current?.setNativeProps({
style: {backgroundColor: 'blue', width: 300},
});
}, 2000);
}, []);
return (
<View style={styles.root}>
<View
ref={viewRef}
style={styles.subView}
onLayout={e => {
console.log(e.nativeEvent);
}}
/>
</View>
);