3.精通React-React组件通信-《前端知识进阶》

admin 2025-11-01 15:33:02 编程 来源:ZONE.CI 全球网 0 阅读模式
  • 1. 父传子通信
  • 2. 子传父通信
  • 3. 父子组件通信案例
  • 4. React中的”插槽”
  • 5. 跨级组件通信
  • 6. 非嵌套组件通信
    • (1)Hooks
    • (2)Redux
    • (3)发布订阅者模式

    在组件之间是存在嵌套关系的,如果我们将一个程序的所有逻辑都放在一个组件中。那么这个组件就会变得臃肿并且难以维护,所以组件化的思想就是对组件进行拆分,再将这些组件嵌套在一起,最终形成我们的应用程序。

    比如,下面的组件就存在如下的关系:

    • App组件是Header、Main、Footer组件的父组件;
    • Main组件是Banner、ProductList组件的父组件;

    image.png在开发的过程中,组件之间是会存在数据通信的,这包括父子组件的通信,兄弟组件之间的通信,祖孙组件之间的通信等等。

    1. 父传子通信

    父子组件之间的通信是通过props来完成的。(1)类组件父传子

    1. class ChildCpn extends Component {
    2. // 实际上下面三行代码就是默认的方式,所以是可以省略的
    3. constructor(props) {
    4. super(props);
    5. }
    6. render() {
    7. const {name, age, height} = this.props;
    8. return (
    9. <h2>子组件展示数据: {name + " " + age + " " + height}</h2>
    10. )
    11. }
    12. }
    13. export default class App extends Component {
    14. render() {
    15. return (
    16. <div>
    17. <ChildCpn name="zhangsan" age="18" height="1.88"/>
    18. <ChildCpn name="lisi" age="20" height="1.98"/>
    19. </div>
    20. )
    21. }
    22. }

    (2)函数组件父传子

    1. function ChildCpn(props) {
    2. const { name, age, height } = props;
    3. return (
    4. <h2>{name + age + height}</h2>
    5. )
    6. }
    7. export default class App extends Component {
    8. render() {
    9. return (
    10. <div>
    11. <ChildCpn name="zhangsan" age="18" height="1.88"/>
    12. <ChildCpn name="lisi" age="20" height="1.98"/>
    13. </div>
    14. )
    15. }
    16. }

    (3)属性验证对于传递给子组件的数据,有时候我们可能希望进行数据格式的验证,特别是对于大型项目来说:

    • 如果项目中默认集成了Flow或者TypeScript,那么直接就可以进行类型验证;
    • 如果没有使用Flow或者TypeScript,也可以通过 prop-types 库来进行参数验证; ```javascript // 第一步:引入prop-types 库 import PropTypes from ‘prop-types’

    // 第二部:设置数据的类型 ChildCpn.propTypes = { name: PropTypes.string, age: PropTypes.nimber, height: PropTypes.number, names: PropTypes.array }

    1. 当对数据进行验证时,如果数据的类型不符,就会报错。
    2. 如果父子组件什么都没传递,我们可以给数据设置默认值,这样就可以显示默认值:
    3. ```javascript
    4. ChildCpn.defaultProps = {
    5. name: "React",
    6. age: 30,
    7. height: 1.88,
    8. names: ["aaa", "bbb", "ccc"]
    9. }

    以上做法在类组件和函数组件中都适用,除了上述方法,在类组件中还可以使用另外一种形式来进行数据验证以及设置默认数据:

    1. class ChildCpn2 extends Component {
    2. // es6中的class fields写法
    3. static propTypes = {
    4. }
    5. static defaultProps = {
    6. }
    7. }

    2. 子传父通信

    说完父传子,下面来说一下子组件向父组件传值。在Vue中,子组件向父组件传值是通过自定义事件来完成的,在React中同样是使用props传递信息,只要让父组件给子组件传递一个绑定了自身上下文的回调函数,那么在子组件中调用这个函数时,就可以将想要交给父组件的数据以函数入参的形式给出去,以此来间接地实现数据从子组件到父组件的流动。

    具体实现步骤如下:

    1. 父组件将回调函数通过 props 传递给子组件;
    2. 子组件把父组件需要的数据信息作为回调函数的参数传递;
    3. 子组件调用该回调函数。

    下面来看一下计数器的案例:

    1. class CounterButton extends Component {
    2. render() {
    3. const { onClick } = this.props;
    4. return <button onClick={ onClick }>+1</button>
    5. }
    6. }
    7. export default class App extends Component {
    8. constructor(props) {
    9. super(props);
    10. this.state = {
    11. counter: 0
    12. }
    13. }
    14. render() {
    15. return (
    16. <div>
    17. <h2>当前计数: {this.state.counter}</h2>
    18. <CounterButton onClick = {e => this.increment()} name="why"/>
    19. </div>
    20. )
    21. }
    22. increment() {
    23. this.setState({
    24. counter: this.state.counter + 1
    25. })
    26. }
    27. }

    这里,我们在父组件定义了一个increment方法,当点击子组件的按钮时,就会触发父组件的方法,并执行该方法,实现数据加一。

    3. 父子组件通信案例

    我们来实现一个菜单栏的切换效果(点击菜单显示不同的内容):image.png样式:

    1. // style.css
    2. .tab-control {
    3. display: flex;
    4. height: 44px;
    5. line-height: 44px;
    6. }
    7. .tab-item {
    8. flex: 1;
    9. text-align: center;
    10. }
    11. .tab-item span {
    12. padding: 5px 8px;
    13. }
    14. .tab-item.active {
    15. color: red;
    16. }
    17. .tab-item.active span {
    18. border-bottom: 3px solid red;
    19. }

    父组件(负责切换前后页面的显示):

    1. // App.js
    2. import React, { Component } from 'react';
    3. import TabControl from './TabControl';
    4. export default class App extends Component {
    5. constructor(props) {
    6. super(props);
    7. this.titles = ['新款', '精选', '流行'];
    8. this.state = {
    9. currentTitle: "新款",
    10. currentIndex: 0
    11. }
    12. }
    13. render() {
    14. const {currentTitle} = this.state;
    15. return (
    16. <div>
    17. <TabControl itemClick={index => this.itemClick(index)} titles={this.titles} />
    18. <h2>{currentTitle}</h2>
    19. </div>
    20. )
    21. }
    22. itemClick(index) {
    23. this.setState({
    24. currentTitle: this.titles[index]
    25. })
    26. }
    27. }

    子组件(只负责页面菜单的切换):

    1. import React, { Component } from 'react';
    2. import PropTypes from 'prop-types';
    3. export default class TabControl extends Component {
    4. constructor(props) {
    5. super(props);
    6. this.state = {
    7. currentIndex: 0
    8. }
    9. }
    10. render() {
    11. const { titles } = this.props;
    12. const {currentIndex} = this.state;
    13. return (
    14. <div className="tab-control">
    15. {
    16. titles.map((item, index) => {
    17. return (
    18. <div key = {item}
    19. className = {"tab-item " + (index === currentIndex ? "active": "")}
    20. onClick = {e => this.itemClick(index)}>
    21. <span>{item}</span>
    22. </div>
    23. )
    24. })
    25. }
    26. </div>
    27. )
    28. }
    29. itemClick(index) {
    30. this.setState({
    31. currentIndex: index
    32. })
    33. const {itemClick} = this.props;
    34. itemClick(index);
    35. }
    36. }
    37. TabControl.propTypes = {
    38. titles: PropTypes.array.isRequired
    39. }

    4. React中的”插槽”

    学过Vue的一定知道,Vue有一个功能就是插槽,插槽方便了组件的自定义,避免了代码的重复。React是没有插槽这个概念的,但是React的灵活性让他比插槽更加好用,下面来看一个导航栏案例:

    样式:

    1. body {
    2. padding: 0;
    3. margin: 0;
    4. }
    5. .nav-bar {
    6. display: flex;
    7. }
    8. .nav-item {
    9. height: 44px;
    10. line-height: 44px;
    11. text-align: center;
    12. }
    13. .nav-left, .nav-right {
    14. width: 70px;
    15. background-color: red;
    16. }
    17. .nav-center {
    18. flex: 1;
    19. background-color: blue;
    20. }

    父组件:

    1. import NavBar1 from './NavBar1';
    2. import NavBar2 from './NavBar2';
    3. export default class App extends Component {
    4. render() {
    5. const leftJsx = <span>aaa</span>;
    6. return (
    7. <div>
    8. // 双标签
    9. <NavBar1 name="" title="" className="">
    10. <span>aaa</span>
    11. <strong>bbb</strong>
    12. <a href="/#">ccc</a>
    13. </NavBar1>
    14. // 单标签
    15. <NavBar2 leftSlot={leftJsx}
    16. centerSlot={<strong>bbb</strong>}
    17. rightSlot={<a href="/#">ccc</a>}/>
    18. </div>
    19. )
    20. }
    21. }

    子组件1:

    1. export default class NavBar extends Component {
    2. render() {
    3. // this.props.children;
    4. return (
    5. <div className="nav-item nav-bar">
    6. <div className="nav-left">
    7. {this.props.children[0]}
    8. </div>
    9. <div className="nav-item nav-center">
    10. {this.props.children[1]}
    11. </div>
    12. <div className="nav-item nav-right">
    13. {this.props.children[2]}
    14. </div>
    15. </div>
    16. )
    17. }
    18. }
    19. // 在这个组件中,父组件向子组件传入了三个元素,在子组件的props中的children中会接收到一个数组,数组中包含了这三个元素
    20. // 当然,这样写是有一定弊端的,因为数组中的元素的数量可能和需要的数量不一致,就有可能将元素渲染位置错误

    子组件2:

    1. export default class NavBar2 extends Component {
    2. render() {
    3. const {leftSlot, centerSlot, rightSlot} = this.props;
    4. return (
    5. <div className="nav-item nav-bar">
    6. <div className="nav-left">
    7. {leftSlot}
    8. </div>
    9. <div className="nav-item nav-center">
    10. {centerSlot}
    11. </div>
    12. <div className="nav-item nav-right">
    13. {rightSlot}
    14. </div>
    15. </div>
    16. )
    17. }
    18. }
    19. // 这父组件中,使用了单标签,使用属性的方式将元素进行传递,在子组件中接收父组件中传递来的元素结构,在进行渲染。
    20. // 这种方式会比上面子组件1的方式好一些。

    这样,我们就实现了插槽的效果。

    5. 跨级组件通信

    跨级组件通信就是父组件与子组件的子组件或者更深层次的通信,通俗点说就是祖先组件与后代组件的通信。这种场景下,我们可以让父组件传给子组件,再让子组件传给他自己的子孙组件,依次逐级传递。这样做当然是可以的,但是当层级关系超过两层时,这种传递方式麻烦且臃肿,不好维护。我们亟需一种解决方案,它可以简化我们一层一层传递 props 的方式。此时 Context 便油然而生,Context 通过组件树提供了一个传递数据的方法,从而避免了在每个层级手动的传递 props 属性。

    祖先组件代码示例:

    1. import React from 'react'
    2. import PropTypes from 'prop-types' // 用于属性校验,想了解更多见文末的扩展阅读。
    3. import Sub from './Sub.js' // 中间组件
    4. export default class App extends React.Component {
    5. // 在父组件定义上下文(Context)
    6. static childContextTypes = { // 声明静态属性 必须要写
    7. color: PropTypes.string, // PropTypes 用于校验属性类型
    8. callback: PropTypes.func // 回调函数
    9. }
    10. getChildContext() { // 用于返回上下文(Context)的值便于后代获取
    11. return {
    12. color: 'pink',
    13. callback: this.callback.bind(this) // 需要绑定this
    14. }
    15. }
    16. callback(msg) {
    17. alert(msg)
    18. }
    19. render() {
    20. return (
    21. <Sub />
    22. )
    23. }
    24. }

    中间组件代码示例:

    1. import React from 'react'
    2. import SubSub from './SubSub.js' // 后代组件
    3. export default function Sub(props) {
    4. return(
    5. <SubSub />
    6. )
    7. }

    后代组件代码示例:

    1. import React from 'react'
    2. import PropTypes from 'prop-types' // 用于属性校验,想了解更多见文末的扩展阅读。
    3. export default class SubSub extends React.Component {
    4. static contextTypes = { // 后代组件必须校验属性类型
    5. color: PropTypes.string,
    6. callback: PropTypes.func
    7. }
    8. render() {
    9. const style = {color: this.context.color} // 通过 this.context 获取上下文的值
    10. const cb = (msg) => {
    11. return () => {
    12. this.context.callback(msg)
    13. }
    14. }
    15. return(
    16. <div style={ style }>
    17. <h1>In SubSub.js</h1> // 粉色字体展示 In SubSub.js
    18. <button onClick={cb('this is SubSub.js')}>click me</button> // 点击按钮,弹出 this is SubSub.js 字样
    19. </div>
    20. )
    21. }
    22. }

    由上可以看出,祖先组件声明了 Context 上下文,后代组件通过 this.context 获取祖先传递下来的内容。

    注意:如果后代组件使用构造函数(constructor),那么 context 需要作为构造函数的第二个参数传入,否则无法使用。

    1. constructor (props, context) {
    2. super(props)
    3. ...
    4. }

    6. 非嵌套组件通信

    (1)Hooks

    开发中经常会遇到这样一个场景,FirstChildSecondChild 是我们的两个组件,FirstChild 组件 dipatch action,在 SecondChild 组件展示变化的数据。那么就需要在两个子组件之上的一层来设计 context。整个设计过程是这样的:

    (1)首先建立 Context,存储一个初始状态和一个变更 state 的状态管理器:

    1. // Context.js
    2. export const defaultState = {
    3. value: 0
    4. }
    5. export function reducer(state, action) {
    6. switch(action.type) {
    7. case 'ADD':
    8. return { ...state, value: state.value + 1 };
    9. case 'REDUCE':
    10. return { ...state, value: state.value - 1 };
    11. default:
    12. throw new Error();
    13. }
    14. }

    (2)需要显性的声明 Context.Provider 把数据传给包裹组件,这里需要使用 useReducer,我们需要把 reducer 和默认的 state 作为 useReducer 的参数传入:

    1. // Content.js
    2. import React, { useReducer, createContext } from 'react'
    3. import FirstChild from './FirstChild'
    4. import SecondChild from './SecondChild'
    5. import { reducer, defaultState } from './Context'
    6. export const Context = createContext(null)
    7. export function Content() {
    8. const [state, dispatch] = useReducer(reducer, defaultState)
    9. return (
    10. <Context.Provider value={{state, dispatch: dispatch}}>
    11. <FirstChild/>
    12. <SecondChild/>
    13. </Context.Provider>
    14. )
    15. }
    1. 组件 FirstChild 有两个按钮 ‘ADD’ 和 ‘REDUCE’,点击两个按钮分别执行加1和减1操作:
      1. import React, { useContext } from 'react'
      2. import { Context } from './Content'
      3. function FirstChild() {
      4. const AppContext = useContext(Context)
      5. return (
      6. <div>
      7. <button onClick={() => { AppContext.dispatch({ type: "ADD" }) }}>ADD</button>
      8. <button onClick={() => { AppContext.dispatch({ type: "REDUCE" }) }}>REDUCE</button>
      9. </div>
      10. )
      11. }
      12. export default FirstChild
      (4)组件 SecondChild 展示当前 state.value :
      1. import React, { useContext } from 'react'
      2. import { Context } from './Content'
      3. function SecondChild () {
      4. const AppContext = useContext(Context)
      5. return (
      6. <div>
      7. {AppContext.state.value}
      8. </div>
      9. )
      10. }
      11. export default SecondChild;

      (2)Redux

      Redux 是一个独立的事件通讯插件。Redux 的基本原理实际上就是围绕着 store 进行的,这个 store 是通过 createStore() 方法创建的,它具有唯一性,可以认为是整个应用的数据存储中心,集中了大部分页面需要的状态数据。想要改变 state 的唯一方法就是触发 ActionReducer接收到 Action 并更新数据 store。按照这个思想,Redux 适用于多交互、多数据源的场景。

      (3)发布订阅者模式

      可以使用 events 插件实现发布订阅者模式,此机制适用于 React 中兄弟组件间的通信。

    首先安装 events:

    1. npm install events -S

    初始化

    1. // events.js
    2. import { EventEmitter } from 'events'
    3. export default new EventEmitter()

    注册监听事件:

    1. // 引入定义的 EventEmitter 实例
    2. import eventEmitter from './events'
    3. eventEmitter.addListener('changeSiblingsData', (msg) => {
    4. this.setState({
    5. bus: msg
    6. })
    7. console.log(msg)
    8. });

    触发:

    1. import eventEmitter from './events'
    2. eventEmitter.emit('changeSiblingsData', msg)

    发布订阅者模式其实就是注册需要的事件,在某些操作的时候,触发该事件即可。它是由事件驱动的。

    以太坊cppgolang区别 编程

    以太坊cppgolang区别

    以太坊是一种去中心化的开源平台,它采用智能合约技术,旨在构建和运行不受干扰的分布式应用程序。作为目前最受欢迎的区块链平台之一,以太坊提供了多种编程语言的支持,其
    progolang 编程

    progolang

    Go语言(Golang)是由Google开发的一门静态类型编程语言。作为一名专业的Golang开发者,我深知这门语言的优势和特点。在本文中,我将介绍Golang
    golangn个发送者 编程

    golangn个发送者

    Golang是一种开源的编程语言,由Google团队开发,旨在提高程序的并发性和简化软件开发过程。在Go语言中,有时需要向多个接收者发送信息。本文将介绍如何在G
    golang技能图谱 编程

    golang技能图谱

    从互联网行业的快速发展到人工智能技术的日益成熟,各种编程语言也应运而生。而在这众多的编程语言中,Golang(即Go)作为一门强大且高效的开发语言备受关注。Go
    评论:0   参与:  10