通信
其实 React 中的组件通信基本和 Vue 中的一致。同样也分为以下三种情况:
- 父子组件通信
- 兄弟组件通信
- 任意组件
父子通信
父组件通过 props
传递数据给子组件,子组件通过调用父组件传来的事件函数传递数据给父组件,这两种方式是最常用的父子通信实现办法。
父向子传值
- 父组件
import {
Component } from "react";
import PropTypes from "prop-types";
export default class Father extends Component {
constructor() {
super();
this.state = {
name:"STEPHEN LING",
}
}
render() {
const {
name } = this.state;
return(
<Child fahterName={
name}/>
)
}
}
- 子组件
import {
Component, Fragment } from "react";
import PropTypes from "prop-types";
export default class