工程化常用的通信方式:
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