19

ReactNative中Props

 3 years ago
source link: http://v2it.win/2020/06/30/reactnative中props/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

一、什么是props

props是属性,用来描述组件的特征,是由父组件传递给子组件的。

二、如何使用props

Mine.js是父组件,传递name给子组件

import React, { Component } from 'react';
import{View}from 'react-native';
import MineView from './MineView';
export default class Mine extends Componment{
  render(){
    return (<View>
        <MineView 
            name = "我的"
        />
    </View>)
  }
}

MineView.js是子组件

import React, { Component } from 'react';
import{Text}from 'react-native';
export default class MineView extends Componment{
  render(){
    return (<Text>Hello,{this.props.name}</Text>)
  }
}

三、什么是默认属性以及它的作用

通过defaultProps定义默认属性,如果上个页面没有传name的话,也能显示默认的值。

static defaultProps={
  name:'首页'
}

四、如何对props进行检查

为了保证上个页面传的属性的正确性,可以PropTypes通过对属性进行类型检查。

使用时需要导入PropTypes

import React,{Component,PropTypes} from 'react'

static propTypes={
  name:PropTypes.string,
}

如何上个页面传的是number类型的话,就会产生类型检查的警告Waring:Failed prop type:Invalid prop ‘name’ of type ‘number’ supplied to ‘PropsTest’.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK