目录
1、父组件向子组件传递数据(Props)
父组件:
import React, { Component } from 'react'
// 引入子组件
import Children from '../Children/Children'
export default class Parent extends Component {
render() {
let curTime = new Date().toLocaleDateString();
curTime = curTime.replaceAll('/',' - ');
return (
<div>
{/* 展示子组件,给子组件传递一个数据 */}
<Children curTime={curTime}/>
</div>
)
}
}
下载 prop-types,给 props 添加约束:
npm i prop-types
import React, { Component } from 'react'
// 引入 prop-types
import propTypes from 'prop-types'
export default class Children extends Component {
// 配置 props 约束
static propTypes = {
// 字符串类型,必须
// curTime:propTypes.string.isRequired // 这样写,即使是空字符串也满足
// 自定义校验方式,第一个参数为一整个props对象,第二个参数为当前约束属性名,第三个对象为当前组件名
curTime:(prop, propName, componentName)=>{
// 当父组件Parent传递字符串为:2023 - 4 - 26 时,输出为
// Object:{curTime:'2023 - 4 - 26'} curTime Children
console.log(prop,propName,componentName);
let temp = prop[propName].split('-');
if(temp.length !== 3){ // 简单的用拆分字符串的形式来检查一下
return new Error('格式错误'); // 校验不通过需要返回一个错误对象,会在控制台中打印
// 即使不通过,返回了一个错误对象,该不满足要求的数据仍然会展示到页面对应位置中
}

文章详细阐述了在React中如何进行组件间的通信,包括父组件通过Props向子组件传递数据,子组件如何通过回调函数向父组件传递数据,以及使用PubSub-js库实现任意组件间的消息订阅与发布,以此实现更灵活的状态管理。
最低0.47元/天 解锁文章
556

被折叠的 条评论
为什么被折叠?



