美文网首页
学习React Native日记三,属性(Props)和状态(s

学习React Native日记三,属性(Props)和状态(s

作者: PreFU | 来源:发表于2016-08-13 17:19 被阅读0次

属性

大多数组件在创建时就可以使用各种参数进行定制。这些参数即是属性。

Image组件为例

import React, { component } from 'react';
import { AppRegistry, Image } from 'react-native';

class Test extends Component {
    render () {
        let path = {
          url: 'https://upload.wikimedia.org/wikipedia/commons/d/de/Bananavarieties.jpg' 
        };
        return ( 
          <Image source = {path} style = {{ width: 193, height: 110 }} />   //{path}将变量赋到JSX语句中,类似于向前端传数据。
        );
    }
}
//括号:表示括号内部的是一个js变量或者表达式,需要执行后赋值。
AppRegistry.registerComponent('Test', () => Test );

自定义组件为例

class Test extends Component {
  render () {
    return (
      <Text> hello  {this.props.name}! </Text>  //此组件中name作为属性进行定制
    );
  }
}

class TestB extends Component {
  render () {
    return (
      <View style = {{alignItems: 'center'}}>
        <Test name = 'White Album' />
        <Test name = 'White Album2' />
      </View>
    );
  }
}

通过此方法编写UI框架

状态

控制组件的数据为两种,一种是属性(props),一种是状态(state)。

class Test extends Component {
  constructor(props) {
    super(props);
    this.state = { showText: True };    //一般在构造器中初始化state.

    setInterval(() => {          //一般不会在定时器中操作state
        this.state = ( { showText:!this.state.showText } );
      },1000);
  }

  render(){
    let value= this.state.showText?this.props.name: '';
    return(
      <Text> {value} </Text>
    )
  }
}

class TestApp extends Component {
  render() {
    return (
      <View>
        <Test name= 'I like ACG' />
        <Test name= 'I like MUSIC' />
        <Test name= 'I like GAME' />
    );
  }
}

理解为状态标志位然后对其进行操作

相关文章

网友评论

      本文标题:学习React Native日记三,属性(Props)和状态(s

      本文链接:https://www.haomeiwen.com/subject/hltysttx.html