【React】归纳篇(九)组件间通信的3中方式之props与订阅发布机制 | subscribe | publish | 改写前面练习

简介: 【React】归纳篇(九)组件间通信的3中方式之props与订阅发布机制 | subscribe | publish | 改写前面练习

组件间通信的2种方式

方式1:通过props传递

  • 1、一般数据–>父组件传递数据给子组件–>子组件读取数据
  • 2、函数数据–>子组件传递数据给父组件–>子组件调用函数
  • 3、共同的数据放在父组件上,特有的数据放在自己组件内部(state)
  • 4、通过props可以传递一般数据和函数数据,只能一层一层传递

方式2:消息订阅(subscribe)与发布(publish)机制

联系: 订阅公众号 (绑定监听)、公众号广播消息 (触发事件)

  • 1、工具库:PubSubJS
  • 2、下载 npm install pubsub-js --save
  • 3、使用

订阅:

import PubSub from 'pubsub-js'
PubSub.subscribe('delete',function(msg,data){})

发布:

import PubSub from 'pubsub-js'
PubSub.publish('delete',data);

###改写前面练习中的代码:评论管理

app.jsx

import React, { Component } from 'react'
import CommentAdd from '../component-add/component-add'
import CommentList from '../component-list/component-list'
import PubSub from 'pubsub-js'
class App extends Component {
  //给组件对象添加指定的state属性  
  state = {
      comments:[
        {username: 'tom',content : 'React哈哈哈'},
        {username: 'yue',content : 'React啊啊啊'},
        {username: 'kang',content : 'React呦呦呦'}
      ]
    }
    componentDidMount() {
      //订阅消息deleteComment
      PubSub.subscribe('deleteComment',(msg,index)=>{
        this.deleteComment(index);
      })
    }
    //添加评论
    addComment = (comment) => {
      const {comments} = this.state;
      comments.unshift(comment);
      //更新状态
      this.setState({comments});
    }
    //删除评论
    deleteComment = (index) => {
      const {comments} = this.state;
      comments.splice(index,1);
      //更新状态
      this.setState({comments});
    }
    render () {
    const {comments} = this.state;
        return (
            <div>
    <header className="site-header jumbotron">
      <div className="container">
        <div className="row">
          <div className="col-xs-12">
            <h1>请发表对React的评论</h1>
          </div>
        </div>
      </div>
    </header>
    <div className="container">
      <CommentAdd addComment = {this.addComment}/>
      <CommentList comments={comments} />
    </div>
  </div>
        )
    }
}
export default App

component-add.jsx

import React, { Component } from 'react'
import PropTypes from 'prop-types'
class CommentAdd extends Component {
    //给组件类添加属性
    static propTypes = {
        addComment: PropTypes.func.isRequired
    }
    //给组件对象添加属性
    state = {
        username: '',
        content: ''
    }
    //使用箭头函数,监听时不用进行bind()
    handleSubmit = () => {
        //搜集数据,并封装为comment对象
        const comment = this.state;
        //更新状态
        this.props.addComment(comment);
        //清除输入数据
        this.setState(
            {   
                username:'',
                content:''
            }
        );
    }
    handleNameChange = (event) => {
        const username = event.target.value;
        this.setState({username});
    }
    handleContentChange = (event) => {
        const content = event.target.value;
        this.setState({content});
    }
    render () {
        const {username,content} = this.state;
        return (
            <div className="col-md-4">
                <form className="form-horizontal">
                    <div className="form-group">
                        <label>用户名</label>
                        <input type="text" className="form-control" placeholder="用户名" value={username} onChange={this.handleNameChange}/>
                    </div>
                    <div className="form-group">
                        <label>评论内容</label>
                        <textarea className="form-control" rows="6" placeholder="评论内容" onChange={this.handleContentChange} value={content}></textarea>
                    </div>
                    <div className="form-group">
                        <div className="col-sm-offset-2 col-sm-10">
                        <button type="button" className="btn btn-default pull-right" onClick={this.handleSubmit}>提交</button>
                        </div>
                    </div>
                </form>
            </div>
        )
    }
}
export default CommentAdd

component-item.jsx

import React, {Component} from 'react'
import PropTypes from 'prop-types'
import PubSub from 'pubsub-js'
import './componentitem.css'
export default class CommentItem extends Component {
    static propTypes = {
        comment: PropTypes.object.isRequired,
        index:PropTypes.number.isRequired
    }
    handleDelete = () => {
        const {comment,deleteComment,index} = this.props;
        //提示
        if(window.confirm('确认删除'+comment.username+'的评论?')) {
            //确认过后再删除
           PubSub.publish('deleteComment',index);
        }
    }
    render() {
        const {comment} = this.props;
        return (
            <li className="list-group-item">
                <div className="handle">
                <a href="javascript:;" onClick={this.handleDelete}>删除</a>
                </div>
                <p className="user"><span >{comment.username}</span><span>说:</span></p>
                <p className="centence">{comment.content}</p>
            </li>
        )
    }
}

component-list.jsx

import React, { Component } from 'react'
import PropTypes from 'prop-types'
import CommentItem from '../component-item/component-item'
import './commentList.css'
class ComponentList extends Component {
    //给组件类添加属性
    static protoTypes = {
        comments: PropTypes.array.isRequired,    }
    render () {
        const {comments} = this.props
        const display = comments.length === 0 ? 'block' : 'none';//是否显示
        return (
            <div className="col-md-8">
                <h3 className="reply">评论回复:</h3>
                <h2 style={{display}}>暂无评论,点击左侧添加评论!!!</h2>
                <ul className="list-group">
                    {
                        comments.map((c,index)=><CommentItem comment={c} key={index} index={index}/>)
                    }
                </ul>
            </div>
        )
    }
}
export default ComponentList

###改写前面练习中的代码:搜索请求

app.jsx

import React, { Component } from 'react'
import Search from './search'
import Main from './main'
class App extends Component {
    state = {
        searchName: ''
    }
    //更新状态
    setSearchName = (searchName) => this.setState({searchName})
    render () {
        return (
            <div className="container">
                <Search/>
                <Main/>
            </div>
        )
    }
}
export default App

search.jsx

import React, { Component } from 'react'
import PropTypes from 'prop-types'
import PubSub from 'pubsub-js'
class Search extends Component {
    handleSearch = () => {
       //得到输入的关键字
       const searchName = this.input.value.trim();
       if(searchName){
           //搜索
          //发布消息(handleSearch)
          PubSub.publish('handleSearch',searchName)
       }
    }
    render () {
        return (
            <section className="jumbotron">
                <h3 className="jumbotron-heading">Search Github Users</h3>
                <div>
                    <input type="text" placeholder="enter the name you search" ref={input=>this.input=input}/>
                    <button onClick={this.handleSearch}>Search</button>
                </div>
            </section>
        )
    }
}
export default Search

main.jsx

import React, { Component } from 'react'
import PropTypes from 'prop-types'
import axios from 'axios'
import PubSub from 'pubsub-js'
class Main extends Component {
    state = {
        initView: true,
        loading: false,
        users: null,
        errorMsg: null
    }
    componentDidMount() {
        //订阅消息(search)
        PubSub.subscribe('handleSearch',(msg,searchName) => {//指定新的searchName,需要发请求
            //更新状态
            this.setState({
                initView:false,
                loading:true
        })
        //发请求
        const url = `https://api.github.com/search/users?q=${searchName}`;
        axios.get(url)
            .then(response => {
                //得到数据
                const result = response.data;
                const users = result.items.map(item=> {
                    return {name:item.login,url:item.html_url,avatarUrl:item.avatar_url}//注意
                }) 
                //更新状态
                this.setState({                    
                    loading:false,
                    users
                })
            })
            .catch(error => {
                //更新状态
                this.setState({
                    loading:false,
                    errorMsg:error.message
                })
            })
        });
    }
    render () {
        const {initView,loading,users,errorMsg} = this.state;
        const {searchName} = this.props;
        if(initView){
            return <h2>请输入关键词进行搜索:{searchName}</h2>
        }else if(loading){
            return <h2>正在请求</h2>
        }else if(errorMsg){
            return <h2>{errorMsg}</h2>
        }else {
            return (
                <div className="row">
                {
                    users.map((user,index)=>(
                        <div className="card" key={index}>
                            <a href={user.url} target="_blank">
                            <img src={user.avatarUrl} style={{width: 100}}/>
                            </a>
                            <p className="card-text">{user.name}</p>
                        </div>
                    ))
                }
                </div>
            )
        }
    }
}
export default Main


相关文章
|
1月前
|
前端开发 API
react怎么实现父子组件传值?
react怎么实现父子组件传值?
|
4天前
|
缓存 前端开发 JavaScript
【亮剑】如何在 React 中点击显示或隐藏另一个组件?
【4月更文挑战第30天】本文介绍了在React中如何通过点击事件控制组件显示与隐藏,包括基础概念和高级应用。使用`useState`钩子和Context API可实现状态驱动的条件渲染,通过CSS类控制组件样式,或利用React Portals在DOM不同位置渲染。性能优化应注意避免不必要的渲染、合理使用Keys、优化事件处理器、使用Memoization及清理资源。测试和验证确保逻辑正确性,以构建动态用户界面并提升应用性能。
|
9天前
|
前端开发 JavaScript 开发者
vue3、react组件数据传值对比分析——父组件传递子组件,子组件传递父组件(二)
vue3、react组件数据传值对比分析——父组件传递子组件,子组件传递父组件
17 0
|
9天前
|
JavaScript 前端开发 算法
vue3、react组件数据传值对比分析——父组件传递子组件,子组件传递父组件(一)
vue3、react组件数据传值对比分析——父组件传递子组件,子组件传递父组件
13 0
|
9天前
|
前端开发 JavaScript 开发者
React的函数组件与类组件:探索两者之间的区别
【4月更文挑战第25天】React提供函数组件和类组件,两者在语法、状态管理、生命周期和性能优化上有所不同。函数组件简单且易于理解,使用 Hooks 可添加状态管理;类组件支持复杂状态管理和生命周期方法,适用于需要精细控制更新的场景。随着 Hooks 的发展,函数组件功能增强,成为更多开发者的首选。选择组件类型应根据实际需求权衡。
|
10天前
|
前端开发
探索React Hooks:一种全新的组件逻辑管理方式
React Hooks是React 16.8版本引入的一项新功能,它改变了我们编写React组件的方式。本文将从Hooks的起源讲起,逐步分析Hooks的优势,并通过具体示例展示Hooks在组件逻辑管理中的应用,旨在帮助读者更好地理解和运用React Hooks。
|
1月前
|
前端开发
React组件通信:如何优雅地实现组件间的数据传递
React组件通信:如何优雅地实现组件间的数据传递
21 0
|
2月前
react+typescript给state和props定义指定类型
react+typescript给state和props定义指定类型
16 1
|
3月前
|
存储 前端开发 中间件
React组件间的通信
React组件间的通信
17 1
|
3月前
|
前端开发 应用服务中间件 数据库
react服务端组件
react服务端组件
21 0