位置: IT常识 - 正文

React props全面详细解析

编辑:rootadmin
props 是 React 组件通信最重要的手段,它在 React 的世界中充当的角色是十分重要的。学好 props 可以使组件间通信更加灵活,同时文中会介绍一些 props 的操作技巧,和学会如何编写嵌套组件 目录

推荐整理分享React props全面详细解析,希望有所帮助,仅作参考,欢迎阅读内容。

文章相关热门搜索词:,内容如对您有帮助,希望把文章链接给更多的朋友!

一、Props 是什么二、props children模式1. props 插槽组件2. render props模式3. render props模式三、进阶实践一、Props 是什么

先来看一个 demo :

function Chidren(){return <div> 我是子组件 </div>}/* props 接受处理 */function Father(props) {const { children , mes , renderName , say ,Component } = propsconst renderFunction = children[0]const renderComponent = children[1]/* 对于子组件,不同的props是怎么被处理 */return (<div>{ renderFunction() }{ mes }{ renderName() }{ renderComponent }<Component /><button onClick={ () => say() } > 触发更改 </button></div> )}/* props 定义绑定 */class App extends React.Component{state={mes: "hello,React"}node = nullsay= () => this.setState({ mes:'let us learn React!' })render(){return <div><Fathermes={this.state.mes} // ① props 作为一个渲染数据源say={ this.say } // ② props 作为一个回调函数 callbackComponent={ Chidren } // ③ props 作为一个组件renderName={ ()=><div> my name is YinJie </div> } // ④ props 作为渲染函数>{ ()=> <div>hello,world</div> } { /* ⑤render props */ }<Chidren /> { /* ⑥render component */ }</Father></div>}}

我们看一下输出结果:

当点击触发更改时就能够调用回调更改数据源:

所以 props 可以是:

① props 作为一个子组件渲染数据源。

② props 作为一个通知父组件的回调函数。

③ props 作为一个单纯的组件传递。

④ props 作为渲染函数。

⑤ render props , 和④的区别是放在了 children 属性上。

⑥ render component 插槽组件。

二、props children模式

我们先来看看 prop + children 的几个基本情况:

1. props 插槽组件<Container><Children></Container>

上述可以在 Container 组件中,通过 props.children 属性访问到 Children 组件,为 React element 对象。

作用:

可以根据需要控制 Children 是否渲染。像上一节所说的, Container 可以用 React.cloneElement 强化 props (混入新的 props ),或者修改 Children 的子元素。

举一个用React.cloneElement 强化 props 的例子,多用于编写组件时对子组件混入新的 props,下面我们要做一个导航组件,我们希望它的结构如下:

<Menu><MenuItem >active</MenuItem><MenuItem>disabled</MenuItem><MenuItem >xyz</MenuItem></Menu>

我们想给每个 MenuItem 子组件都添加 index 属性,这个事情不应该让用户手动添加,最好是可以在 Menu 组件中自动为每个 MenuItem 子组件添加上,并且 Menu 组件还应该判断子组件的类型,如果子组件的类型不是 MenuItem 组件就报错。

React props全面详细解析

Menu.tsx:

const Menu: React.FC<MenuProps> = (props) => {// ... 一些操作const renderChildren = () => { // 让子级的children都是 menuItem,有不是的就报错return React.Children.map(children, (child, index) => {const childElement = child as React.FunctionComponentElement<MenuItemProps>const { displayName } = childElement.typeif(displayName === 'MenuItem' || displayName === "SubMenu") {return React.cloneElement(childElement, { index: index.toString() })} else {console.error('warning: Menu has a child whitch is not a MenuItem')}})}return (<ul className={classes} style={style} data-testid="test-menu"><MenuContext.Provider value={passedContext}>{renderChildren()}</MenuContext.Provider></ul>)}

在 Menu 组件中我们通过 React.children.map 来循环子组件,通过 child.type 可以获取到每个子组件的 displayName 静态属性,这个在子组件中有定义:

通过子组件的 displayName 来判断是否是我们需要的 MenuItem,如果是的话就调用 React.cloneElement 来为子组件添加 index 属性。

2. render props模式<Container>{ (ContainerProps)=> <Children {...ContainerProps} /> }</Container>

这种情况,在 Container 中, props.children 属性访问到是函数,并不是 React element 对象,我们应该调用这个函数:

function Container(props) {const ContainerProps = {name: 'alien',mes:'let us learn react'}return props.children(ContainerProps)}

这种方式作用是:

1 根据需要控制 Children 渲染与否。

2 可以将需要传给 Children 的 props 直接通过函数参数的方式传递给执行函数 children 。

3. render props模式

如果 Container 的 Children 既有函数也有组件,这种情况应该怎么处理呢?

<Container><Children />{ (ContainerProps)=> <Children {...ContainerProps} name={'haha'} /> }</Container>const Children = (props)=> (<div><div>hello, my name is { props.name } </div><div> { props.mes } </div></div>)function Container(props) {const ContainerProps = {name: 'alien',mes:'let us learn react'}return props.children.map(item=>{if(React.isValidElement(item)){ // 判断是 react elment 混入 propsreturn React.cloneElement(item,{ ...ContainerProps },item.props.children)}else if(typeof item === 'function'){return item(ContainerProps)}else return null})}const Index = ()=>{return <Container><Children />{ (ContainerProps)=> <Children {...ContainerProps} name={'haha'} /> }</Container>}

这种情况需要先遍历 children ,判断 children 元素类型:

针对 element 节点,通过 cloneElement 混入 props ;针对函数,直接传递参数,执行函数。三、进阶实践

实现一个简单的<Form> <FormItem>嵌套组件

接下来到实践环节了。需要编写一个实践 demo ,用于表单状态管理的<Form>和<FormItem>组件

<Form>用于管理表单状态;<FormItem>用于管理<Input>输入框组件。,

编写的组件能够实现的功能是:

①Form组件可以被 ref 获取实例。然后可以调用实例方法submitForm获取表单内容,用于提交表单,resetForm方法用于重置表单。

②Form组件自动过滤掉除了FormItem之外的其他React元素

③FormItem中 name 属性作为表单提交时候的 key ,还有展示的 label 。

④FormItem可以自动收集<Input/>表单的值。

App.js:

import React, { useState, useRef } from "react";import Form from './Form'import FormItem from './FormItem'import Input from './Input'function App () {const form = useRef(null)const submit =()=>{/* 表单提交 */form.current.submitForm((formValue)=>{ // 调用 form 中的submitForm方法console.log(formValue)})}const reset = ()=>{/* 表单重置 */form.current.resetForm() //调用 form 中的 resetForm 方法}return <div className='box' ><Form ref={ form } ><FormItem name="name" label="我是" ><Input /></FormItem><FormItem name="mes" label="我想对大家说" ><Input /></FormItem><FormItem name="lees" label="ttt" ><Input /></FormItem></Form><div className="btns" ><button className="searchbtn" onClick={ submit } >提交</button><button className="concellbtn" onClick={ reset } >重置</button></div></div>}export default App

Form.js:

class Form extends React.Component{state={formData:{}}/* 用于提交表单数据 */submitForm=(cb)=>{cb({ ...this.state.formData })}/* 获取重置表单数据 */resetForm=()=>{const { formData } = this.stateObject.keys(formData).forEach(item=>{formData[item] = ''})this.setState({formData})}/* 设置表单数据层 */setValue=(name,value)=>{this.setState({formData:{...this.state.formData,[name]:value}})}render(){const { children } = this.propsconst renderChildren = []React.Children.forEach(children,(child)=>{if(child.type.displayName === 'formItem'){const { name } = child.props/* 克隆`FormItem`节点,混入改变表单单元项的方法 */const Children = React.cloneElement(child,{key:name , /* 加入key 提升渲染效果 */handleChange:this.setValue , /* 用于改变 value */value:this.state.formData[name] || '' /* value 值 */},child.props.children)renderChildren.push(Children)}})return renderChildren}}/* 增加组件类型type */Form.displayName = 'form'

设计思想:

首先考虑到<Form>在不使用forwardRef前提下,最好是类组件,因为只有类组件才能获取实例。创建一个 state 下的 formData属性,用于收集表单状态。要封装重置表单,提交表单,改变表单单元项的方法。要过滤掉除了FormItem元素之外的其他元素,那么怎么样知道它是不是FormItem,这里教大家一种方法,可以给函数组件或者类组件绑定静态属性来证明它的身份,然后在遍历 props.children 的时候就可以在 React element 的 type 属性(类或函数组件本身)上,验证这个身份,在这个 demo 项目,给函数绑定的 displayName 属性,证明组件身份。要克隆FormItem节点,将改变表单单元项的方法 handleChange 和表单的值 value 混入 props 中。

FormItem.js:

function FormItem(props){const { children , name , handleChange , value , label } = propsconst onChange = (value) => {/* 通知上一次value 已经改变 */handleChange(name,value)}return <div className='form' ><span className="label" >{ label }:</span>{React.isValidElement(children) && children.type.displayName === 'input'? React.cloneElement(children,{ onChange , value }): null}</div>}FormItem.displayName = 'formItem'

设计思想:

FormItem一定要绑定 displayName 属性,用于让<Form>识别<FormItem />
本文链接地址:https://www.jiuchutong.com/zhishi/311680.html 转载请保留说明!

上一篇:Java 中的Double Check Lock(转)(java中double是什么数据类型)

下一篇:织梦ckeditor编辑器升级为ckeditor4-word图片自动上传mp4播放批量图片上传(织梦怎样实现文件上传)

  • 北京市增值税发票
  • 所得税分录是怎么计算的
  • 印花税计提时应入什么科目
  • 增值税销项税额账务处理
  • 土地增值税会计核算
  • 出纳与会计现金对不上
  • 母子公司换股协议
  • 税控盘维护费开的是普票可以抵扣吗
  • 报税期能不能开发票
  • 上市公司回购优先股
  • 收到捐赠货物的会计分录怎么写
  • 报销购物卡发票公司如何交税?
  • 写字楼出租流程
  • 结转已到期未兑付怎么办
  • 审计人员用餐费用
  • 出售商标使用权收入计入什么科目
  • 权益资本成本率计算
  • 民办非企业单位是私立还是公立
  • 海关进口增值税怎么认证抵扣
  • 出口用的增值税税率
  • 个税缴纳期数填1是什么意思
  • 小规模企业所得税按季度还是按年
  • 增值税销项税额抵减账务处理
  • 收取违约金如何入账
  • Win10 20H2 Beta 预览版 19042.782正式推送(附更新内容)
  • 已删除好友的聊天记录
  • ecap.exe是什么
  • 购买其他权益工具
  • 存货什么时候计提什么时候回转
  • 滴滴打车开具的电子发票可以抵扣吗
  • yolo目标识别
  • js中move
  • discuzq开发
  • 人工费没有发票咋入帐
  • 社保公司承担部分计入哪个科目
  • python转换数字
  • 发票金额是含税价还是不含税价
  • 库存商品转出
  • 企业增值税申报流程
  • 特殊收入如何计税
  • 增值税是指怎样计算的
  • 新收入准则确认收入的条件
  • 产品广告费属于什么会计科目类别
  • 应税服务零税率是什么
  • 一次开票分期确认收入
  • 因质量问题对方直接扣款也不开票
  • 委托收款的业务场景有哪些
  • 金蝶财务软件固定资产
  • 旅游团建费用会计怎么入账
  • 财政拨付注册资金怎么填
  • 出售短期债券投资发生的净损失计入哪里
  • mysql数据库迁移上云
  • 镜的镜像截图
  • xp电脑显示屏显示不全
  • 如何进入opencore引导
  • win8系统设置错误
  • xp系统java环境变量配置
  • win10系统如何关闭杀毒软件和防火墙
  • win10 ie浏览器双击没有反应
  • linux tar -czvf
  • win8怎么改系统
  • android游戏开发论文
  • g8a1
  • unity手机游戏开发教程
  • 实用的批处理命令
  • 笔记本电脑没有鼠标怎么多选文件
  • 批处理设置ip地址配置的dns
  • 没有实例化是什么意思
  • vue+vue-validator 表单验证功能的实现代码
  • dos跳转到指定目录
  • unity投影交互开发
  • bootstrap学习
  • js实现复制文本
  • js常用继承
  • 面向对象的编程语言更适合大规模编程
  • 全国税务发票查询电话
  • 收到虚开增值税专用发票怎么处理
  • 河南省地方税务局公告2017年第4号
  • 美丽重生李晓晓免费阅读
  • 买二手房土地证怎么过户
  • 免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

    鄂ICP备2023003026号

    网站地图: 企业信息 工商信息 财税知识 网络常识 编程技术

    友情链接: 武汉网站建设