组件、属性和状态

组件、属性和状态是React Native框架里面的内容,在React VR中也适用

属性和状态

组件里面有两种类型的数据:props(属性)和state(状态),属性是由父组件设置的,在组件的生命周

期内都有效,而那些需要改变的数据,我们用state(状态)来改变

props

大多数的组件在创建后都有不同的参数,这些参数也叫做props.

你自己的组件也可以用属性,在你的app里面很多地方都可以用这个组件,在每个地方做些微的改

变就可以了,下面就是 this.props 的用法:

import React, { Component } from 'react';

import { AppRegistry, asset, Pano, Text, View } from 'react-vr';


class Greeting extends Component {

  render() {

    return (

      <Text>Hello {this.props.name}!</Text>

    );

  }

}


class LotsOfGreetings extends Component {

  render() {

    return (

      <View>

        <Pano source={asset('chess-world.jpg')}/>

        <View style={'{{'}transform: {'[{'}translate: [0, 0, -3]{'}]}}'}>

          <Greeting name='Rexxar'/>

          <Greeting name='Jaina'/>

          <Greeting name='Valeera'/>

        </View>

      </View>

    );

  }

}


AppRegistry.registerComponent('LotsOfGreetings', () => LotsOfGreetings);

用name属性,我们可以复用Greeting组件

state

一般情况下,我们在构造函数中初始化state数据,用setState来改变state的数据

import React, { Component } from 'react';

import { AppRegistry, asset, Pano, Text, View } from 'react-vr';


class Blink extends Component {

  constructor(props){

    super(props);

    this.state = {showText: true};


    // Toggle the state every second

    setInterval(() => {

      this.state ({ showText: !this.state.showText {'})'};

    }, 1000);

  }


  render() {

     let  display = this.state.showText ? this.props.text : ' ';

    return (

      <Text> {display}</Text>

    );

  }

}


class BlinkApp extends Component {

  render() {

    return (

      <View>

        <Pano source={asset('chess-world.jpg')}/>

        <View style={'{{'}transform: {'[{'}translate: [0, 0, -3]{'}]}}'}>

          <Blink name='I love to blink'/>

          <Blink name='Yes blinking is so great'/>

          <Blink name='Why did they ever take this out of HTML'/>

          <Blink name='Look at me look at me look at me'/>

        </View>

      </View>

    );

  }

}


AppRegistry.registerComponent('BlinkApp', () => BlinkApp);

state的用法和React里面的用法是一样的,更多state的资料可以去查下React.Component API.