热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

【React】8props的children、校验、默认值

【React】8props的children、校验、默认值1.props.children属性2.props校验3.props默认值1.props.children属性child

【React】8 props的children、校验、默认值

  • 1. props.children 属性
  • 2. props 校验
  • 3. props默认值


1. props.children 属性
  • children 属性:表示组件标签的子节点。当组件标签有子节点时,props就会有该属性。
  • chidren 属性与普通的props一样,值可以是任意值(文本、React元素、组件,甚至是函数)

demo:

import React from 'react'
import ReactDOM from 'react-dom/client'//组件1
class User extends React.Component {render() {return (// 传入非函数children// hello// //传入函数children<Node1>{() &#61;> console.log("函数1")}</Node1>)}
}//组件
const Node1 &#61; (props) &#61;> {//使用函数childrenprops.children()return (//使用非函数children//

node1--{props.children}
<div>node1--</div>)
}const root &#61; ReactDOM.createRoot(document.getElementById("root"))
root.render(<User />)

效果&#xff1a;
在这里插入图片描述

2. props 校验

使用步骡

  1. 安装包 prop-types ( yarn add prop-types / npm i prop-types )
  2. 导入 prop-types包&#xff0c;import PropTypes from &#39;prop-types&#39;&#xff1b;
  3. 使用组件名.propTypes &#61;{} 来给组件的props添加校验规则
  4. 按验规见面过 PropTypes象来指定

import React from &#39;react&#39;
import ReactDOM from &#39;react-dom/client&#39;
//导入校验包
import PropTypes from &#39;prop-types&#39;//组件
const Node1 &#61; (props) &#61;> {console.log(props)return (<div>node1--{props.colors[0]}</div>)
}//添加校验规则
Node1.propTypes &#61; {colors: PropTypes.array
}const root &#61; ReactDOM.createRoot(document.getElementById("root"))
// root.render()
root.render(<Node1 colors&#61;{"qq"} />)}

效果&#xff1a;
传入错误参数时&#xff0c;会提示类型错误
在这里插入图片描述
常用验证规则&#xff1a;
若是必填则后面加.isRequired

MyComponent.propTypes &#61; {// You can declare that a prop is a specific JS primitive. By default, these// are all optional.optionalArray: PropTypes.array,optionalBool: PropTypes.bool,optionalFunc: PropTypes.func,optionalNumber: PropTypes.number,optionalObject: PropTypes.object,optionalString: PropTypes.string,optionalSymbol: PropTypes.symbol,// Anything that can be rendered: numbers, strings, elements or an array// (or fragment) containing these types.
//验证是否为节点optionalNode: PropTypes.node,//验证是否为元素// A React element (ie. ).optionalElement: PropTypes.element,//验证是否为元素类型// A React element type (ie. MyComponent).optionalElementType: PropTypes.elementType,//验证是否为另一个类的实例// You can also declare that a prop is an instance of a class. This uses// JS&#39;s instanceof operator.optionalMessage: PropTypes.instanceOf(Message),//验证传入值是否在给定范围// You can ensure that your prop is limited to specific values by treating// it as an enum.optionalEnum: PropTypes.oneOf([&#39;News&#39;, &#39;Photos&#39;]),//验证传入类型是否在给定范围// An object that could be one of many typesoptionalUnion: PropTypes.oneOfType([PropTypes.string,PropTypes.number,PropTypes.instanceOf(Message)]),// An array of a certain typeoptionalArrayOf: PropTypes.arrayOf(PropTypes.number),// An object with property values of a certain typeoptionalObjectOf: PropTypes.objectOf(PropTypes.number),// You can chain any of the above with &#96;isRequired&#96; to make sure a warning// is shown if the prop isn&#39;t provided.// An object taking on a particular shapeoptionalObjectWithShape: PropTypes.shape({optionalProperty: PropTypes.string,requiredProperty: PropTypes.number.isRequired}),// An object with warnings on extra propertiesoptionalObjectWithStrictShape: PropTypes.exact({optionalProperty: PropTypes.string,requiredProperty: PropTypes.number.isRequired}),requiredFunc: PropTypes.func.isRequired,// A value of any data typerequiredAny: PropTypes.any.isRequired,// You can also specify a custom validator. It should return an Error// object if the validation fails. Don&#39;t &#96;console.warn&#96; or throw, as this// won&#39;t work inside &#96;oneOfType&#96;.
//回调函数&#xff1a;自定义验证规则customProp: function(props, propName, componentName) {if (!/matchme/.test(props[propName])) {return new Error(&#39;Invalid prop &#96;&#39; &#43; propName &#43; &#39;&#96; supplied to&#39; &#43;&#39; &#96;&#39; &#43; componentName &#43; &#39;&#96;. Validation failed.&#39;);}},// You can also supply a custom validator to &#96;arrayOf&#96; and &#96;objectOf&#96;.// It should return an Error object if the validation fails. The validator// will be called for each key in the array or object. The first two// arguments of the validator are the array or object itself, and the// current item&#39;s key.customArrayProp: PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName) {if (!/matchme/.test(propValue[key])) {return new Error(&#39;Invalid prop &#96;&#39; &#43; propFullName &#43; &#39;&#96; supplied to&#39; &#43;&#39; &#96;&#39; &#43; componentName &#43; &#39;&#96;. Validation failed.&#39;);}})
};

3. props默认值

指定 props 的默认值&#xff0c; 这个方法只有浏览器编译以后才会生效

class HandsomeBoy extends Component{// 设置默认值//defaultProps 可以为 Class 组件添加默认 props,基于 static 的写法static defaultProps &#61; {name:&#39;pyq&#39;}constructor(props){super(props)}render(){return <section>{this.props.name}</section>}
}

指定 props 的默认值&#xff0c;这个方法会一直生效

class Age extends Component{render(){return <section>{this.props.name}</section>}
}
// 默认值的第二种,指定 props 的默认值&#xff0c;这个方法会一直生效
Age.defaultProps &#61; {name:18
}


推荐阅读
  • npminstall-Dbabelcorebabelpreset-envbabelplugin-transform-runtimebabelpolyfillbabel-loader ... [详细]
  • loader资源模块加载器webpack资源模块加载webpack内部(内部loader)默认只会处理javascript文件,也就是说它会把打包过程中所有遇到的 ... [详细]
  • 如何在Vue项目中安装和使用VUX组件?
    vux2模板fork自webpack模板,基本和官方同步。1、默认为webpack2模板npminstallvue-cli-g如果还没安装vueinitairyla ... [详细]
  • 本文介绍了OC学习笔记中的@property和@synthesize,包括属性的定义和合成的使用方法。通过示例代码详细讲解了@property和@synthesize的作用和用法。 ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • 不同优化算法的比较分析及实验验证
    本文介绍了神经网络优化中常用的优化方法,包括学习率调整和梯度估计修正,并通过实验验证了不同优化算法的效果。实验结果表明,Adam算法在综合考虑学习率调整和梯度估计修正方面表现较好。该研究对于优化神经网络的训练过程具有指导意义。 ... [详细]
  • VueCLI多页分目录打包的步骤记录
    本文介绍了使用VueCLI进行多页分目录打包的步骤,包括页面目录结构、安装依赖、获取Vue CLI需要的多页对象等内容。同时还提供了自定义不同模块页面标题的方法。 ... [详细]
  • node.jsrequire和ES6导入导出的区别原 ... [详细]
  • Jquery 跨域问题
    为什么80%的码农都做不了架构师?JQuery1.2后getJSON方法支持跨域读取json数据,原理是利用一个叫做jsonp的概念。当然 ... [详细]
  • Vue基础一、什么是Vue1.1概念Vue(读音vjuː,类似于view)是一套用于构建用户界面的渐进式JavaScript框架,与其它大型框架不 ... [详细]
  • React 小白初入门
    推荐学习:React官方文档:https:react.docschina.orgReact菜鸟教程:https:www.runoob.c ... [详细]
  • RN即ReactNative基于React框架针对移动端的跨平台框架,在学习RN前建议最好熟悉下html,css,js,当然如果比较急,那就直接上手吧,毕竟用学习前面基础的时间,R ... [详细]
  • 头几天想写个小爬虫顺序,预备后端就用koa2。因而翻遍github与各大网站,都没找到一个好用的、轻一点的koa2脚手架,也找不到一个清楚些的搭建引见。github上的脚手架要么是 ... [详细]
  • POJ 1046 Color Me Less
    ColorMeLessTimeLimit: 1000MS MemoryLimit: 10000KTotalSubmissions: 31449 Accept ... [详细]
  • SparkRDD宽窄依赖及Stage划分
    1.术语解释:Master(Standalone):资源管理的主节点(进程)ClusterManager:在集群上获取资源的外部服务(例如standalone,Mesos,Yarn ... [详细]
author-avatar
烟为你吸_811
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有