基礎(chǔ)篇章:關(guān)于 React Native 的props,state,style的講解

React Native看起來很像React,其實(shí)React Native就是根據(jù)React發(fā)展而來的,只不過其基礎(chǔ)組件是原生組件而非web組件。所以在體驗(yàn)交互上更加接近原生操作,所以體驗(yàn)比web效果好很多。加上可以跨平臺(tái),體驗(yàn)又接近原生,所以自15年以來比較火。

我們要想理解React Native應(yīng)用的基本結(jié)構(gòu),我們首先需要先了解一些基本的React的概念,比如JSX語法、組件、state狀態(tài)以及props屬性。所以這篇我們重點(diǎn)講講Props,state和style樣式。今天講解的內(nèi)容,都是根據(jù)React Native官方文檔上的內(nèi)容來的。
官方文檔地址:
Props :
[https://facebook.github.io/react-native/docs/props.html]
state:
[https://facebook.github.io/react-native/docs/state.html]
style:
[https://facebook.github.io/react-native/docs/style.html]

props

props(屬性) 概念

大多數(shù)組件在創(chuàng)建的時(shí)候就可以用各種參數(shù)來進(jìn)行定制。用于定制的這些參數(shù)就稱為props(屬性)。所謂props,就是屬性傳遞,而且是單向傳遞的。屬性多的時(shí)候,可以傳遞一個(gè)對(duì)象,這是es6中的語法。

例子1:

官網(wǎng)給的第一個(gè)例子是用現(xiàn)成的一個(gè)Image基礎(chǔ)組件來解釋這個(gè)概念的,例子如下:

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

class Bananas extends Component {
  render() {
    let pic = {
      uri: 'https://upload.wikimedia.org/wikipedia/commons/d/de/Bananavarieties.jpg'
    };
    return (
      <Image source={pic} style={{width: 193, height: 110}}/>
    );
  }
}

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

當(dāng)我們創(chuàng)建一個(gè)image圖片的時(shí)候,我們可以使用名為source的props屬性去控制這個(gè)image顯示什么圖片。

注意{pic}外圍有一層括號(hào),我們需要用括號(hào)來把pic這個(gè)變量嵌入到JSX語句中。我們可以把任意合法的JavaScript表達(dá)式通過括號(hào)嵌入到JSX語句中。

為了更好的說明props的用法和概念,我把上面的例子又修改了一下,我的這個(gè)例子只是為了更好的說明props屬性的用法,不建議大家這么使用,畢竟image是現(xiàn)成的基礎(chǔ)組件。

修改后的例子:

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

class Bananas extends Component {
  render() {
    return (
      <Image source={this.props.image} style={{width: 120, height: 80}}/>
    );
  }
}

class FirstProject extends Component {
  render() {
    let pic = {
      uri: 'https://upload.wikimedia.org/wikipedia/commons/d/de/Bananavarieties.jpg'
    };
    return (
      <View style={{padding: 10}}>
        <Bananas image ={pic}/>
      </View>
    );
  }
}

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

這里我自定義了一個(gè)名為Bananas的組件,定義了一個(gè)名為image的屬性props,注意image是小些的, 大些的Image是官方圖片基礎(chǔ)組件。在自定義的Bananas組件中的Image組件中,引用了我們定義的image的屬性props。這樣一對(duì)比,可能大家就更能清楚的理解了props的用法了。說白了就是定制參數(shù),然后傳值。

例子2

官方給的第二個(gè)例子,就非常清楚了,是這樣的。

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

class Greeting extends Component {
  render() {
    return (
      <Text>Hello {this.props.name}!</Text>
    );
  }
}

class LotsOfGreetings extends Component {
  render() {
    return (
      <View style={{alignItems: 'center'}}>
        <Greeting name='Rexxar' />
        <Greeting name='Jaina' />
        <Greeting name='Valeera' />
      </View>
    );
  }
}

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

意思就是:自定義了一個(gè)名為Greeting的組件,然后,屬性名為name,傳不同的name值,在Text顯示不同的名字。

state

React靠一個(gè)state來維護(hù)狀態(tài),當(dāng)state發(fā)生變化則更新DOM??刂埔粋€(gè)組件,一般有兩種數(shù)據(jù)類型,一種是props,一種是state。props是在父組件中設(shè)置,一旦指定,它的生命周期是不可以改變的。對(duì)于組件中數(shù)據(jù)的變化,我們是通過state來控制的。

一般情況下,我們初始化state狀態(tài),是在constructor構(gòu)造函數(shù)中,然后如果需要改變時(shí),我們可以調(diào)用setState方法。官方給的例子時(shí)一個(gè)閃爍的文字的例子,看看官網(wǎng)的例子是如何制作文字閃爍效果的。

例子

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

class Blink extends Component {
  constructor(props) {
    super(props);
    this.state = { showText: true };

    // 每1000毫秒對(duì)showText狀態(tài)做一次取反操作
    setInterval(() => {
      this.setState({ showText: !this.state.showText });
    }, 1000);
  }

  render() {
    // 根據(jù)當(dāng)前showText的值決定是否顯示text內(nèi)容
    let display = this.state.showText ? this.props.text : ' ';
    return (
      <Text>{display}</Text>
    );
  }
}

class BlinkApp extends Component {
  render() {
    return (
      <View>
        <Blink text='I love to blink' />
        <Blink text='Yes blinking is so great' />
        <Blink text='Why did they ever take this out of HTML' />
        <Blink text='Look at me look at me look at me' />
      </View>
    );
  }
}

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

首先,它是自定義了一個(gè)Blink的組件,在構(gòu)造函數(shù)中初始化了state,然后寫了一個(gè)定時(shí)器,每個(gè)1秒改變一次狀態(tài),然后setState,然后在渲染render()方法中,判斷狀態(tài)的變化,如果是true,顯示文字,false顯示空。這樣一閃一閃的效果就出來了。

然后我們?cè)贐linkApp中使用Blink組件,并傳入我們需要的文字內(nèi)容即可。

效果圖如下:



其實(shí)在實(shí)際開發(fā)中,我們不需要設(shè)置定時(shí)器來改變狀態(tài),一般情況下,我們都是在獲取到服務(wù)器的數(shù)據(jù)時(shí)或者用戶輸入時(shí),更新狀態(tài)去顯示最新的數(shù)據(jù)。這是我們就是通過setState來做到的。

style

在React Native中我們不需要使用什么特殊的語言或者語法去定義樣式,我們還是使用JavaScript來寫樣式。所有的核心組件都接受名為style的屬性。唯一的不同就是屬性樣式的命名使用了駝峰命名法,例如將background-color改為backgroundColor。

例子:

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

class FirstProject extends Component {
  render() {
    return (
      <View>
        <Text style={styles.red}>just red</Text>
        <Text style={styles.bigblue}>just bigblue</Text>
        <Text style={[styles.bigblue, styles.red]}>bigblue, then red</Text>
        <Text style={[styles.red, styles.bigblue]}>red, then bigblue</Text>
        <Text style={{color:'red' , fontSize:30}}>
            非著名
      <Text style={{color:'blue'}}>
          程序員
      </Text>
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  bigblue: {
    color: 'blue',
    fontWeight: 'bold',
    fontSize: 30,
  },
  red: {
    color: 'red',
  },
});

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

在js中,最簡(jiǎn)單的樣式用法是style屬性可以是一個(gè)普通的JavaScript對(duì)象。但是這里我們可以傳入一個(gè)數(shù)組的樣式,在數(shù)組中位置后面的樣式覆蓋前面的樣式,后面的優(yōu)先級(jí)比較高。所以我們可以這樣使用去繼承樣式。

隨著組件的復(fù)雜性,我們建議使用StyleSheet.create來集中定義組件的樣式,就像上面的用法一樣,當(dāng)然也支持單獨(dú)的使用,就像上面例子中的最后一個(gè)的用法,上面文字的展示中,第三個(gè),第四個(gè)使用了數(shù)組樣式的方法,后面的樣式覆蓋了前面的樣式,最后一個(gè)使用了內(nèi)嵌的方式,做成了前半部分顯示紅色,后半部分顯示藍(lán)色的效果。

效果圖如下:


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容