Raect Native之五 props的使用

本文深入讲解React中的Props概念,包括其定义、使用方法、默认属性设置及类型检查。通过实例演示了Props的传递、默认值设定与PropTypes的使用,帮助开发者掌握组件间的数据传递技巧。

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

  1. 什么是props?
    大多数组件在创建时就可以使用各种参数来进行定制。用于定制的这些参数就称为props

  2. 如何使用props?

    export default class PropsView extends Component {
        render() {
            var  params = {name:'zhangsan', age:19,sex:'女'}
            var {name,sex} = params;
            return <View>
                    {/* <PropsUse {...params}/> */}
                    <PropsUse name={name} sex={sex}/>
                </View>
        }
    }
    
       export default class PropsUse extends Component{
           static defaultProps={
              name:'小红',
              age:10,
              sex:'男',
           }
       
           static propTypes={
              name:PropTypes.string,
              age:PropTypes.int,
              sex:PropTypes.string.isRequired,
           }
           render(){
              
               return <View>
                       <Text style={{fontSize:26}}>你好, { this.props.name} </Text>
                       <Text style={{fontSize:26}}>年龄: { this.props.age}</Text>
                       <Text style={{fontSize:26}}>性别: { this.props.sex}</Text>
               </View> 
           }
       }
    
  3. 什么是默认属性以及它的作用?
    static defaultProps 设置默认属性,当前一个界面没有数据传过来时,
    使用默认赋值

      static defaultProps={
              name:'小红',
              age:10,
              sex:'男',
           }
            ```
    
  4. 如何对props进行约束和检查?
    PropTypes 进行约束和检查
    name:PropTypes.string 数据类型进行约束
    sex:PropTypes.string.isRequired isRequired非null检查

       import PropTypes from 'prop-types';
       static propTypes={
          name:PropTypes.string,
          age:PropTypes.int,
          sex:PropTypes.string.isRequired,
    }
    
    
  5. props的使用技巧

    1. 扩展运算符{…}
       var  params={name:'zhangsan', age:19,sex:'女'}
       {...params}
    
    1. 结构赋值
       var  params = {name:'zhangsan', age:19,sex:'女'}
       var {name,sex} = params;
       return <View>
                   <PropsUse name={name} sex={sex}/>
               </View>
    

练习项目

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值