位置: 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播放批量图片上传(织梦怎样实现文件上传)

  • 转让无形资产可以免税吗
  • 我国流转税的税种有哪些
  • 预计负债的三个基本要素
  • 个人生产经营所得税
  • 公司员工的伙食费计入什么科目
  • 结转以前的其他业务成本如何做会计分录呢?
  • pos机刷卡的银行有哪些
  • 当月预交增值税时所属期选了上期怎么办
  • 无法确认退货率时,差错更正为啥不反转增值税
  • 出售无形资产的会计科目
  • 一般纳税人当月只有进项没有销项怎么做账
  • 印刷专票税率是几个点
  • 应税销售额含不含税
  • 增值税税负率行业标准2022年
  • 航空运输的湿租业务按什么缴纳增值税
  • 受托加工物资产生的成本怎么做会计核算?
  • 资产减值损失月末需要结转吗
  • 建筑公司购买材料需要写备注
  • 增值税免税项目和免征增值税的区别
  • 未开票收入如何记账
  • vmware10虚拟机安装
  • linux网卡lo
  • php字符串定义
  • 发票已认证还能作废吗2020
  • 未入账发票可以作废吗
  • 苹果客服人工24小时
  • 宾馆一次性用品有哪些
  • 资产评估增值是什么意思
  • pytorch ln
  • php管理员和用户登录
  • php soap wsdl
  • 真菌感染手指甲空了
  • vscode插件大全
  • 新政府会计制度科目解读
  • ftp port命令
  • fmt println
  • 前期认证相符且不符合
  • 财政总预算会计的主体是
  • centos安装nmtui
  • 织梦的css样式在哪
  • 公司向股东借的钱怎么还
  • 分公司可以独立开票吗
  • mysql sqlyog
  • mysql分片sql
  • 企业汇算清缴的工资薪金支出是怎么填
  • 民间非营利组织会计制度及操作实务
  • 开发票价格能否比实际金额高?
  • 以房抵债会计分录怎么做
  • 长期挂账其他应付款处理
  • 支付金额小于发票怎么办
  • 存货管理的类型
  • 生产成本要如何核算
  • 技术服务费如何赋码
  • 担保公司的担保费能退吗
  • 怎么解释税收
  • 主营业务收入一定要结转成本吗
  • 员工报销停车费计入什么科目
  • 专利的费用计入成本吗
  • win10 mysql 5.6.35 winx64免安装版配置教程
  • windowsxp关机没反应
  • slmgr.vbs /dli
  • win10打开或关闭
  • Linux怎么删除文件第一行
  • win7远程桌面连接命令
  • windows8.1更新windows10
  • 苹果Mac OS X通知中心提示音怎么修改 OS X通知中心提示音更换方法图解
  • 使用自带DISM工具修复Windows8.1映像
  • suse linux 12 sp5
  • cocos2d android 游戏开发学习——CCAction(二)
  • 复制链接
  • css ie6 ie7 ff的CSS hack使用技巧
  • jquery中点击事件点击没动静
  • socketio视频教程
  • 深入探讨换个说法怎么说
  • no android facet found
  • 国家税务局级别排名
  • 深圳买新房契税怎么收
  • 延安市地方税务局电话
  • 税务检查调账通知书
  • 怎么注册山东省采购网
  • 免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

    鄂ICP备2023003026号

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

    友情链接: 武汉网站建设