React native (4)--props、state、style、布局

1.属性:props

render() { return( <Text>Hello {this.props.name}</Text> ); } 使用 <View style={{flex:1,flexDirection:'column'}}> <Greeting name="sinstar"/> <Greeting name="cos"/> </View>

2 状态 state

constructor(props) {
      super(props);
      this.state = {showText: true}

      //1000毫秒对showText状态做一次取反操作
      setInterval(() => { this.setState({showText: !this.state.showText}); },1000); } render(){ let display = this.state.showText ? this.props.text : ' '; return( <Text>{display}</Text> ) } //使用 ----------------------------------- <BlinkTest text="aaa"/>

3.样式

export default class Greeting extends Component { render() { return( <Text style={styles.red}>Hello {this.props.name}</Text> // <View style={{width:300,height:200,backgroundColor:'red'}}></View> // <View style={{flex: 1,backgroundColor: 'powderblue'}} /> // <View style={{flex: 2,backgroundColor: 'skyblue'}} /> // <View style={{flex: 3,backgroundColor: 'steelblue'}} /> ); } } const styles=StyleSheet.create({ red:{ color:'red',fontSize:30 } }) 

下面是布局

  1. flex 类似安卓的layout—weight
 flexDirection:'column':竖向 flexDirection:'row' :横向 return ( <View style={{flex:1,flexDirection:'column'}}> <Greeting name="sinstar"/> <Greeting name="cos"/> <BlinkTest text="aaa"/> <View style={{width:300,backgroundColor:'red'}}></View> <View style={{flex: 1,backgroundColor: 'powderblue'}} /> <View style={{flex: 2,backgroundColor: 'skyblue'}} /> <View style={{flex: 3,backgroundColor: 'steelblue'}} /> </View> );

5.Justify Content

在组件的style中指定justifyContent可以决定其子元素沿着主轴的排列方式。子元素是应该靠近主轴的起始端还是末尾段分布呢?亦或应该均匀分布?对应的这些可选项有:flex-start、center、flex-end、space-around以及space-between。

// 尝试把`justifyContent`改为`center`看看 // 尝试把`flexDirection`改为`row`看看 <View style={{ flex: 1,flexDirection: 'column',justifyContent: 'space-between',}}> <View style={{width: 50,height: 50,backgroundColor: 'powderblue'}} /> <View style={{width: 50,backgroundColor: 'skyblue'}} /> <View style={{width: 50,backgroundColor: 'steelblue'}} /> </View>

Align Items

在组件的style中指定alignItems可以决定其子元素沿着次轴(与主轴垂直的轴,比如若主轴方向为row,则次轴方向为column)的排列方式。子元素是应该靠近次轴的起始端还是末尾段分布呢?亦或应该均匀分布?对应的这些可选项有:flex-start、center、flex-end以及stretch。

注意:要使stretch选项生效的话,子元素在次轴方向上不能有固定的尺寸。以下面的代码为例:只有将子元素样式中的width: 50去掉之后,alignItems: ‘stretch’才能生效。

// 尝试把`alignItems`改为`flex-start`看看 // 尝试把`justifyContent`改为`flex-end`看看 // 尝试把`flexDirection`改为`row`看看 <View style={{ flex: 1,justifyContent: 'center',alignItems: 'center',backgroundColor: 'steelblue'}} /> </View> );

相关文章

react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...
react 本身提供了克隆组件的方法,但是平时开发中可能很少使...
mobx 是一个简单可扩展的状态管理库,中文官网链接。小编在接...
我们在平常的开发中不可避免的会有很多列表渲染逻辑,在 pc ...