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

2023-10-07 18:19:58 浏览数 (2)

组件间通信的2种方式
方式1:通过props传递
  • 1、一般数据–>父组件传递数据给子组件–>子组件读取数据
  • 2、函数数据–>子组件传递数据给父组件–>子组件调用函数
  • 3、共同的数据放在父组件上,特有的数据放在自己组件内部(state)
  • 4、通过props可以传递一般数据和函数数据,只能一层一层传递
方式2:消息订阅(subscribe)与发布(publish)机制

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

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

订阅:

代码语言:javascript复制
import PubSub from 'pubsub-js'
PubSub.subscribe('delete',function(msg,data){})

发布:

代码语言:javascript复制
import PubSub from 'pubsub-js'
PubSub.publish('delete',data);

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

代码语言:javascript复制
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

代码语言:javascript复制
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

代码语言:javascript复制
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

代码语言:javascript复制
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

代码语言:javascript复制
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

代码语言:javascript复制
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

代码语言:javascript复制
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

0 人点赞