热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

React项目基础教程第五课:深入解析组件间通信机制

1.组件间通信 1.1 props 子->父组件->子 class Search extends Component { handleClick = () => { const { na

1.组件间通信

1.1 props

子->父组件->子

class Search extends Component {
 handleClick = () => {
    const { name } = this.state;
    if (name) {
      this.props.setSearchName(name);
    }
  };
import Search from "./search";
import Main from "./main";
class Users extends Component {
  constructor(props) {
    super(props);
    this.state = {
      searchName: ""
    };
  }
  setSearchName = searchName => {
    this.setState({
      searchName
    })
  };
  render() {
    return (
      
); } } export default Users;
import propTypes from "prop-types";
import "./index.less";
import axios from "axios";
class Main extends Component {
  static propTypes = {
    searchName: propTypes.string.isRequired
  };
  constructor(props) {
    super(props);
    this.state = {...};
  }
  componentWillReceiveProps(newProps) {
    const { searchName } = newProps;
    this.setState({... });
    const url = `https://api.github.com/search/users?q=${searchName}`;
    axios .get(url).then()
1.2 pubsubjs

yarn add pubsub-js

import PubSub from "pubsub-js";
class Search extends Component {
  handleClick = () => {
    const { name } = this.state;
    if (name) {
      // this.props.setSearchName(name);
      // 发布消息(search)
      PubSub.publish("search", name);
    }
  };
import PubSub from "pubsub-js";
class Main extends Component {
  componentDidMount() {
    // 订阅消息(search)
    PubSub.subscribe("search", (msg, searchName) => {
      console.log(msg, searchName);
      this.setState({...});
      const url = `https://api.github.com/search/users?q=${searchName}`;
      axios.get(url).then();
1.3 redux

推荐阅读
author-avatar
只爱裙装
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有