zoukankan      html  css  js  c++  java
  • React 学习(六) 组件通信

    Components Communication

    Parent and Child Component

    • Class Component

      import React, { Component } from "react";
      class ChildCpn extends Component {
        render() {
          const { name, age, height } = this.props;
          return (
            <div>
              <h2>Subclass:{name + " " + age + " " + height}</h2>
            </div>
          );
        }
      }
      
      export default class App extends Component {
        render() {
          return (
            <div>
              <ChildCpn name="Smallstars" age="18" height="1.83" />
              <ChildCpn name="BlackAngel" age="20" height="1.63" />
            </div>
          );
        }
      }
      
    • Function Component

      import React, { Component } from "react";
      
      function ChildCpn(props) {
        const { name, age, height } = props;
      
        return (
          <div>
            <h2>Subclass:{name + " " + age + " " + height}</h2>
          </div>
        );
      }
      
      export default class App extends Component {
        render() {
          return (
            <div>
              <ChildCpn name="Smallstars" age="18" height="1.83" />
            </div>
          );
        }
      }
      

    Cross Components Communication

    • Props are passed layer by layer

      import React, { Component } from "react";
      
      const ProfileHeader = (props) => {
        const { nickname, age } = props;
        return (
          <div>
            <div>nickname: {nickname}</div>
            <div>age: {age}</div>
          </div>
        );
      };
      
      const Profile = (props) => {
        const { nickname, age } = props;
      
        return (
          <div>
            <ProfileHeader nickname={nickname} age={age} />
          </div>
        );
      };
      
      class App extends Component {
        constructor(props) {
          super();
      
          this.state = {
            nickname: "Smallstars",
            age: 18,
          };
        }
      
        render() {
          const { nickname, age } = this.state;
          return (
            <div>
              <Profile nickname={nickname} age={age} />
            </div>
          );
        }
      }
      
      export default App;
      
    • Context Sharing and Delivery

      // Class Component
      import React, { Component } from "react";
      
      // First, create the context object
      const UserContext = React.createContext({
        nickname: "defaultName",
        level: 0,
      });
      
      class ProfileHeader extends Component {
        render() {
          // console.log("ProfileHeader", this);
          const { context } = this;
          return (
            <div>
              <h2>nickname: {context.nickname}</h2>
              <h2>level: {context.level} </h2>
            </div>
          );
        }
      }
      
      class Profile extends Component {
        render() {
          // console.log("Profile", this);
          return (
            <div>
              <div>
                <ProfileHeader></ProfileHeader>
              </div>
            </div>
          );
        }
      }
      
      // Fourth, get the shared data
      ProfileHeader.contextType = UserContext;
      
      export default class App extends Component {
        constructor() {
          super();
          this.state = {
            nickname: "Smallstars",
            level: 10,
          };
        }
      
        render() {
          return (
            <>
              {/* Second, sharing the data */}
              <UserContext.Provider value={this.state}>
                {/* Third, components that use shared data must be subcomponent */}
                <Profile />
              </UserContext.Provider>
              {/* use the default value */}
              <Profile />
            </>
          );
        }
      }
      
      // Function Component
      import React, { createContext } from "react";
      
      // First, create the context
      const UserContext = createContext({
        nickname: "defaultName",
        level: 0,
      });
      
      const ThemeContext = createContext({
        red: "red",
      });
      
      const ProfileHeader = () => {
        return (
          // Fourth, user the Consumer and call the function pass in the value
          <UserContext.Consumer>
            {(userValue) => {
              return (
                // Fifth, mulit level nested calls, as the Fluter
                <ThemeContext.Consumer>
                  {(themeValue) => {
                    // console.log(themeValue);
                    return (
                      <>
                        <div style={{ color: themeValue.color }}>
                          nickname: {userValue.nickname}
                        </div>
                        <div>level: {userValue.level}</div>
                        <div>color: {themeValue.color}</div>
                      </>
                    );
                  }}
                </ThemeContext.Consumer>
              );
            }}
          </UserContext.Consumer>
        );
      };
      
      const Profile = () => {
        return (
          <div>
            <ProfileHeader />
          </div>
        );
      };
      
      const App = () => {
        const user = {
          nickname: "smallstars",
          level: 100,
        };
      
        return (
          // Second, sharing the data
          <UserContext.Provider value={user}>
            <ThemeContext.Provider value={{ color: "blue" }}>
              {/* Third, as a subcomponent */}
              <Profile />
            </ThemeContext.Provider>
          </UserContext.Provider>
        );
      };
      
      export default App;
      
    • Events

      import React, { PureComponent } from "react";
      
      import { EventEmitter } from "events";
      
      // Event bus
      const eventBus = new EventEmitter();
      
      class Home extends PureComponent {
        // addListener
        componentDidMount() {
          eventBus.addListener("btnClick", this.handleBtnClickListener);
        }
      
        // removeListener
        componentWillUnmount() {
          // remove all event listener about btnClick
          // eventBus.removeListener("btnClick")
      
          // Only one needs to be cancelled separately
          // and there use the ... operator
          eventBus.removeListener("btnClick", this.handleBtnClickListener);
        }
      
        handleBtnClickListener = (message, num) => {
          console.log(message, num);
        };
      
        render() {
          return <div>Home</div>;
        }
      }
      
      class Profile extends PureComponent {
        render() {
          return (
            <div>
              Profile
              <button
                onClick={(e) => {
                  this.btnClick();
                }}
              >
                Click
              </button>
            </div>
          );
        }
      
        btnClick() {
          // emit the event
          eventBus.emit("btnClick", "HelloWorld", 123);
        }
      }
      
      export default class App extends PureComponent {
        render() {
          return (
            <div>
              <Home></Home>
              <Profile></Profile>
            </div>
          );
        }
      }
      
    • Redux[^redux]

    每天进步一点点
  • 相关阅读:
    咏码农
    IDisposable 的 Visual C# 模板
    PDF补丁丁(0.3.2.13测试版)新增光学字符识别(OCR)功能,将图片 PDF 文档的目录转换为书签
    PDF 补丁丁开发计划列表及已知问题
    PDF补丁丁0.3.3.9测试版(新增 PDF 文档结构探查器)
    PDF补丁丁(0.3.2.14测试版)优化提取PDF页面功能,删除PDF页面更方便
    PDF补丁丁(0.3.2.1测试版)新增光学字符识别(OCR)功能,识别 PDF 文档图片的文字
    PDF 补丁丁0.3.2 即将发布正式版
    PDF 补丁丁0.3.2版正式发布(新增PDF OCR,加强自动生成书签、书签编辑器等功能)
    PDF 补丁丁 0.3.3.10 测试版(新增结构探查器可编辑 PDF 文档)
  • 原文地址:https://www.cnblogs.com/smallstars/p/14043591.html
Copyright © 2011-2022 走看看