3.0 react之props

本文介绍了React中组件间常见的通信方式,包括props用于父子组件间的数据传递以及使用pubsub-js实现订阅发布模式的消息交互。同时,强调了props的只读性,说明组件不应修改自身的props,并展示了如何在React函数组件和类组件中使用props传递样式对象。此外,还提到了使用PropTypes进行类型检查以确保传入数据的正确性。
摘要由CSDN通过智能技术生成

工程化常用的通信方式:

1):props父子组件消息传递

2):pubsub-js

概念:PubSub消息订阅与发布;

安装:yarn add pubsub-js

使用:

1.引入:import PubSub from “pubsub-js”

2.发布消息

3.在ComponentDidMount中订阅消息

4.在ComponentWillUnMount中取消订阅

props的只读性

组件无论是使用 函数声明 还是通过 class 声明,都绝不能修改自身的 props。

props 是组件定义属性的集合。是组件对外的接口。由外部通过 JSX 属性传入数据。外部组件通过 props 来和当前组件进行数据对话

在 React 中,props 的属性值可以是任何数据类型(基本数据类型、函数、对象…),非字符串数据类型在 JSX 中,必须用花括号 {} 把 prop 值给包裹起来。这也是为什么 style 有两层花括号的原因:最外层代表 JSX 语法,意味着它是一个变量对象;内层花括号 {}代表的是一个对象。

//函数组件
function Button(props){
    const btnStyles = {
        width: props.style.width,
        height: props.style.height,
        background: props.style.background,
        color: props.style.color,
        border: props.style.border,
        outline: props.style.outline,
        cursor: props.style.cursor,
    };
    return (
        <div>
            <button style={btnStyles}>按钮</button>
        </div>
    )
}

//定义样式
const btnStyle = {
    width:"100px",
    height:"40px",
    background:"orange",
    color:"#ffffff",
    border:"none",
    outline:"none",
    cursor:"pointer"
};

//渲染到页面
ReactDOM.render(<Button style={btnStyle}/>,document.getElementById("example"));
//类组件
class Button extends React.Component{
    constructor(props){
        super(props);
    };
    render(){
        //console.log(this.props);
        const btnStyles = {
            width: this.props.style.width,
            height: this.props.style.height,
            background: this.props.style.background,
            color: this.props.style.color,
            border: this.props.style.border,
            outline: this.props.style.outline,
            cursor: this.props.style.cursor,
        };
        return(
            <div>
                <button style={btnStyles}>按钮</button>
            </div>
        )
    }
}

//定义样式
const btnStyle = {
    width:"100px",
    height:"40px",
    background:"orange",
    color:"#ffffff",
    border:"none",
    outline:"none",
    cursor:"pointer"
};

//渲染到页面
ReactDOM.render(<Button style={btnStyle}/>,document.getElementById("example"));

以上,通过两种方式定义了 React 组件,都使用了 props 来进行数据的传递。

使用 PropTypes 进行类型检查

使用 PropTypes 进行类型检查,可以规范传入数据的类型。借用第三方库 prop-types 来解决这一问题。

命令端安装:

npm install --save prop-types
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值