(精华)2020年8月10日 React-Native 布局与样式

RN布局与样式

一款好的App离不开漂亮的布局,RN中的布局方式采用的是FlexBox(弹性布局)

FlexBox提供了在不通尺寸设备上都能保持一致的布局方式

flexBox

宽和高

尺寸是没有单位的
​运行在android上的时候 100dp
iso 的时候 100pt
字体会被解释成16sp

像素无关

和而不同

​ RN中FlexBox和Web Css上FlexBox工作方式是一样的,但有些地方还是有出入的

​ flexDirection:

​ RN中默认是flexDirection:‘column’,Web Css中默认是 flex-direction:‘row’

​ alignItems:

​ RN中默认alignItems: ‘stretch’,在Web Css中默认 align-items:‘flex-start’

​ flex:

​ RN中只接受一个属性,Web css 可以接受多个属性:flex: 2 2 10%

​ 不支持的属性: align-content flex-basis order flex-flow flex-grow flex-shrink

Flex in RN

​ 以下属性是RN所支持的Flex属性

​ 容器属性

​ 项目属性

​ alignSelf

​ auto(default) 元素继承了父容器的align-item属性,如果没有则为’stretch’

​ stretch

​ center

​ flex-start

​ flex-end

​ flex:定义了一个元素可伸缩的能力,默认是0

样式

属性与状态

RN中使用两种数据来控制一个组件:propsstateprops是在父组件中指定,而且一经指定,在被指定的组件的生命周期中则不再改变。 对于需要改变的数据,我们需要使用state

具体在页面中使用

import React, { Component } from 'react';
import {
  View,
  Text,
  StyleSheet
} from 'react-native';

class PropsPage extends Component {
  constructor(props) {
    super(props)
    this.state = {
      showText: ''
    }
  }
  componentDidMount () {
    setTimeout(() => {
      this.setState({
        showText: '软谋教育前端课程'
      })
    }, 1000)
  }
  render () {
    const { showText } = this.state
    const show = showText ? 'none' : 'flex'
    return (
      <View style={styles.container}>
        <Text style={{ display: show }}>loading....</Text>
        <Text style={styles.text}>{showText}</Text>
        <TextShow name={'子组件'}></TextShow>
      </View>
    )
  }
}
function TextShow (props) {
  return (
    <View>
      <Text>{props.name}</Text>
    </View>
  )
}

export default PropsPage;
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'blue'
  },
  text: {
    color: '#fff'
  }
})

猜你喜欢

转载自blog.csdn.net/aa2528877987/article/details/107921887
今日推荐