React Native基本语法

本文概述了React Native的基本语法,包括Component、props与state的使用,生命周期方法,页面跳转,以及组件间的通信方式。讲解了如何在React Native中定义组件、处理props和state,介绍了组件的生命周期,如挂载、更新和卸载状态,以及如何在不同页面和组件之间传递数据。此外,还提到了ES6的语法特性,并分享了一些开发React Native的实用技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

React Native真的是越来越流行,没使用React Native开发项目都不好意思说自己是搞客户端开发的。对于纯Native开发者来说,刚上手React Native有一定的适应期,如果JavaScript也不熟练的话那就更悲催了。React Native涉及ES6,React语法,JSX,前端调试,Native客户端等知识,本文简单总结了React Native开发中一些知识点。算是在学习中的积累。

Component

Component:组件,使用React.createClass或者extends React.Component创建的类为组件。
Element:元素或者可以说是组件的实例,使用<Label />或者let label = new Label()创建的为实例。

对于定义组件,React以前版本的写法(ES5):

var Lable  = React.createClass({

    render(){

    }
});

React最新的写法(ES6):

class Label extends React.Component{
    render(){
    }
}

props与state

props属性:组件可以定义初始值,自己不可更改props属性值,只允许从父组件中传递过来:

// 父组件
class MainComponent extends React.Component{
    render(){
        return(<Label name="标题栏">);
    }
}

// 子组件
class Label extends React.Component{
    render(){
        return(<Text>{this.props.name}</Text>);
    }
}

父组件向Label传递name=”标题栏”的props属性,在Label中使用this.props.name引用此属性。

state属性:组件用来改变自己状态的属性,通常使用setState({key:value})来改变属性值,不能使用this.state.xxx来直接改变,setState({key:value})方法会触发界面刷新。

对于经常改变的数据且需要刷新界面显示,可以使用state。对于不需要改变的属性值可以使用props。React Native建议由顶层的父组件定义state值,并将state值作为子组件的props属性值传递给子组件,这样可以保持单一的数据传递。

在以前版本的React中定义state,props可以使用生命周期方法 getInitialState()getInitialState():

var Label = React.createClass({
    getInitialState(){
        key:value,
        ...
    },
    getInitialProps(){
        key:value,
        ...
    },// 这种写法需要有,不要使用;
    render:funation(){

    }
});

在最新版本的React可以使用构造函数替代getInitialState(),getInitialState()方法定义初始值:


class Label extends React.Component{
   
    constructor(props) {
        super(props);
        this.state = {
            time: '2016',
            city: '上海',
        };
        this.props = {
            name:'标题',
        };
    }
}

默认props与props校验


class Label extends React.Component{
   
    constructo
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值