兩篇文章搞定ReactNative之搞定RectJS

RootDOM

ReactJS 采用Virtual DOM的方式來代替JS原生的DOM操作方式來提高頁面的響應(yīng)速度,但是Virtual DOM同樣需要掛在在用一個實體的DOM上,因此首先要創(chuàng)建一個根DOM來支撐后面所有的事

mReactInstanceManager = ((ReactApplication) getApplication()).getReactNativeHost().getReactInstanceManager();
Bundle bundle = new Bundle();
ReactRootView = reactRootView = new ReactRootView(this);
reactRootView.startReactApplication(mReactInstanceManager, "port", bundle);
import { AppRegistry } from 'react-native';
import App from './src/App';

AppRegistry.registerComponent('port', () => App);

如上的reactRootView 就是我們創(chuàng)建的RootDOM,ReactNative通過字符串"port"進行訪問和綁定,所有后面的事情我們將在這個基礎(chǔ)上進行,比如上面代碼,將App頁面對象綁定在了"port"上。

組件(Component)

在ReactJS中一切都是組件。通過組件的狀態(tài),切換,組合來完成復(fù)雜的頁面效果

export default class NoticeBar extends Component {
    render(){
        return(
            <View></View>
        );
    }
}

組件屬性(Props)

ReactJS 采用JSX(類XML表達式)語法,Props 就類似與XML的attribute。Props 是只讀的,組件內(nèi)部無論是方法還是類都無法更其值

class Me extends Component {
    render(){
        return(
            <View>
                <Text>{this.props.name}</Text>
            </View>
        );
    }
}
class Root extends Component{
    render(){
        return(
            <View>
                <Me name={"pq"}/>
            </View>
        );
    }
}

如上代碼,name是Me組件的Props,在Me內(nèi)部不能修改name的值,只能通過this.props.name來獲取name屬性的值

屬性默認值

屬性是組件外部傳入的值,很多時候是選擇性的傳值,因此需要給一些不是必須的屬性設(shè)置默認值,來做錯誤處理或是其他:

static defaultProps={
    source:"",
    height:12
}
屬性類型限定(PropTypes)

JS中變量可以說是無類型的,在ReactJS中可以做類型限定(新版使用'prop-types'庫)

static propTypes = {
    title: PropTypes.string,
    isUpdate: PropTypes.bool,
    count: PropTypes.number,
    callback: PropTypes.func
}
狀態(tài)提升

狀體提升就是將自身狀態(tài)通過Props回調(diào)的方法向上傳遞給父組件

class Me extends Component {

    updateAge(age){
        this.props.callback(age);
    }
    render(){
        return(
            <View>
                <Text>{this.props.name}</Text>
            </View>
        );
    }
}
class Root extends Component{
    render(){
        return(
            <View>
                <Me name={"pq"} callback={age=>console.log(age)}/>
            </View>
        );
    }
}

如上代碼中,當Me組件執(zhí)行updateAge后,將通過callback屬性向上傳遞,最終在callback方法中打印age

組件狀態(tài)(State)

Props是只讀的,由外到內(nèi)的傳值。這兒State則是維系組件內(nèi)部狀態(tài)的變量,驅(qū)動組件更新的鞭子。
state是組件(Component)內(nèi)部維系的一個對象,通過this.state.*進行對預(yù)定變量的讀取,以及通過this.setState({})對預(yù)定state變量進行修改

注意:

1.直接給state賦值:this.state.data=[1,2,3]是無效的。state變量的更改應(yīng)當通過setState進行。
2.this.props,this.state都是異步更新的值,setState同樣是異步的
3.setState會進行狀態(tài)合并更新比如setState({name:"123",age:23}),狀態(tài)更新的時候會合并name及age的更新

初始化state
 this.state={data:[]};
更改state
this.setState({data:[1,2,3]});

聲明周期(Life)

在Android或是IOS中,每一個UI組件都是有生命周期的,同樣在ReactJS中組件也是有生命周期的

constructor(props){
    super(props);
}
componentWillMount(){

}
componentDidMount(){

}
componentDidUpdate(prevProps, prevState){

}
componentWillUnmount(){

}
componentWillReceiveProps(nextProps){

}
render(){

}

1.重點看componentWillReceiveProps,當組件Props被父組件更新的時候會在這個方法里面收到
2.當setState執(zhí)行后,render方法會重新執(zhí)行,以改變組件內(nèi)容

組件引用

在原生的JS中我們可以通過document.getElementById("abc")來操作DOM,在ReactJS中則不這么用,因為這兒都是虛擬的DOM。但是我還是有需要在組件外調(diào)用組件內(nèi)方法的需求,所以就有了組件對象引用。

class Me extends Component {

    updateAge(age){
        this.props.callback(age);
    }
    render(){
        return(
            <View>
                <Text>{this.props.name}</Text>
            </View>
        );
    }
}
class Root extends Component{
    let meComponent=null;
    updateage(){
        this.refs.me.updateAge(12);
        this.meComponent.updateAge(14);
    }
    render(){
        return(
            <View>
                <Me ref="me" name={"pq"} callback={age=>console.log(age)}/>
                <Me ref={(myref)=>meComponent=myref} name={"pq"} callback={age=>console.log(age)}/>
            </View>
        );
    }
}

上面代碼中,在Root組件中我們寫了兩個Me組件,ref的值就是組件的ID,第一個使用了靜態(tài)的字符串ID,第二個使用了箭頭函數(shù)的賦值操作,引用的是ReactJS自己生成的ID,在Root的updateage方法中分別對這兩個組件的updateAge方法進行了操作。這兩種方式是等價的。

ReactJS官方說明,除非必要,不要使用組件引用。如果確實需要,則推薦用箭頭函數(shù)的方式代替靜態(tài)賦值的方式
應(yīng)當盡量使用setState的方式進行組件更新

條件渲染

JSX中可以通過不同的條件來渲染不同的組件或是屬性,下面一個用三目運算符進行條件渲染的例子

class Me extends Component {
    render(){
        return(
            <View>
                <Text>{this.props.name}</Text>
            </View>
        );
    }
}
class Root extends Component{
    state={
        name:"fox"
    };
    render(){
        return(
            <View>
                {this.state.name==="fox"?
                    <Me name={"Firefox"} />:
                    <Text>“Chrome”</Text>}
            </View>
        );
    }
}

當state.name等于'fox'的時候渲染Me組件,否則渲染Text組件

List&Keys

當組件內(nèi)含有ListVIew或是某一組件的子組件為同一類型的組件時,ReactJs會將這些組件當做列表。
Keys可以在DOM中的某些元素被增加或是刪除的時候幫轉(zhuǎn)React識別是哪些元素發(fā)生了變化。因此在寫代碼的時候應(yīng)當為每一個子組件元素給予一個確定的標識key。元素的key只有在它和它的兄弟節(jié)點對比時才有意義,但是元素的key在兄弟組件之間都應(yīng)該是唯一的,就像五胞胎兄弟名字叫東南西北中一樣。

用map生成list

const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
  <li key={number.toString()}>
    {number}
  </li>
);

在組件中寫一些相同的子組件

<View>
    <Text style={{backgroundColor: "#0f0"}} key={0}>今天北京晴天,大約10-20攝氏度</Text>
    <Text style={{backgroundColor: "#00f"}} key={1}>去往長城的乘客請走八達嶺高速</Text>
    <Text style={{backgroundColor: "#ff0"}} key={2}>今天動物園人山人海</Text>
    <Text style={{backgroundColor: "#f0f"}} key={3}>一定要登上長城,做好漢</Text>
    <Text style={{backgroundColor: "#0ff"}} key={4}>美女,明天,后天,沒了</Text>
</View>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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