国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

react 組件之間的通信(父子組件)

這篇具有很好參考價(jià)值的文章主要介紹了react 組件之間的通信(父子組件)。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問(wèn)。

一、父子組件

React中 組件內(nèi)調(diào)用其他組件不需要進(jìn)行 類似于vue 聲明組件(components)

React 組件內(nèi)調(diào)用其他組件 直接將組件導(dǎo)入 放置在對(duì)應(yīng)的JSX 代碼中

父子組件通信(傳統(tǒng)):

1、父組件->子組件 ?通過(guò)屬性傳遞

2、子組件->父組件 ?父組件通過(guò)將自身的函數(shù)對(duì)象傳遞給子組件, 子組件執(zhí)行父組件傳遞的函數(shù)來(lái)修改/傳值操作

練習(xí)一:

Father:

import { Component } from 'react'

import Son from './Son';

class Father extends Component {

  /* constructor(props){
    super(props);

    this.state = {
      person: {
        name: '張三',
        age: 200
      }
    }
  }
 */
  state = {
    person: {
      name: '張三',
      age: 200
    },

    arr: [1,2,3]
  }

  render() {
    return (
      <div className='container'>
        <h1>Father組件:</h1>
        <ul>
          {
            this.state.arr.map( item => (
              <li key={item}>{item}</li>
            ) )
          }
        </ul>

        <hr/>

        {/* 
          通過(guò) 自定義屬性 vperson 將 this.state.person 傳遞給 Son
        
          const vadd = (e, item) => this.handleAddArray(e.vitem);

          vadd(event, 1000)
        */}
        <Son vperson={this.state.person} varr={this.state.arr} vhandle={this.handleAge.bind(this)} vadd={ (e, vitem) => this.handleAddArray(e, vitem)}/>
      </div>
    )
  }


  handleAge(){

    this.setState({
      person: {...this.state.person, age: this.state.person.age +1 }
    });
  }

  handleAddArray(e, item){
    console.log('子組件調(diào)用父組件 handleAddArray..........');
    // 向 arr 中末尾追加新元素
    this.state.arr.push(item);

    this.setState({
      arr: this.state.arr
    });

  }
}

export default Father;

Son:

import { Component } from 'react'

class Son extends Component {

  /* 
  子組件 通過(guò)constructor 函數(shù)中的props 形參 接受 父組件 傳遞的所有屬性

  注: 子組件內(nèi)不允許修改/更新 父組件所傳遞的 props
  */
  constructor(props){
    super(props);

    console.log('Son props=>', props);

  }

  render() {
    const {  vperson  } = this.props;
    return (
      <div>
        <h1 className="h1">Son</h1>
        <h3 className='h3'>
        {/*   {this.props.vperson.name}
          {this.props.varr} */}
  
          {vperson.name} --- {vperson.age}
        </h3>
        <button className="btn btn-primary" onClick={this.add.bind(this)}>增加年齡</button>

        <button className="btn btn-success" onClick={this.localadd.bind(this)}>增加arr數(shù)組元素</button>

      </div>
    )
  }

  add(){
    // 調(diào)用父組件傳遞的 handleAge 函數(shù)
    this.props.vhandle();
  }

  localadd(e){
    this.props.vadd(e, new Date().getTime());
  }
}

export default Son;

練習(xí)二:

Father:

import { Component } from 'react'

import Son from './Son';

class Father extends Component {

  state = {
    tabs : [
      {
        tid: '001',
        title: '我的',
        isActive: true
      },
      {
        tid: '002',
        title: '收藏',
        isActive: false
      },
      {
        tid: '003',
        title: '設(shè)置',
        isActive: false
      }
    ]
  }

  render() {
    const {tabs} = this.state;
    return (
      <div className="container">
        <h1>Father組件</h1>
        <hr/>
        <Son tabsProps={tabs}  changeItem={ selectedId => this.changeItem(selectedId) }/>
      </div>
    )
  }

  changeItem(selectedID){
    console.log('子組件調(diào)用父組件 changeItem 獲取tab id=>', selectedID);

    // 根據(jù) selectedID 值 匹配 this.tabs 數(shù)組中的元素 如果匹配修改isActive=true 如果不匹配 isActive=false

    this.state.tabs.forEach( item => {
      if(item.tid === selectedID) item.isActive = true;
      else item.isActive = false;
    } )

    this.setState({
      tabs: this.state.tabs
    });
  }
}

export default Father

Son:

import { Component } from 'react'

/* 
子組件接受 props 可以省略 constructor函數(shù)接受props , 直接通過(guò) this.props獲取父組件傳遞的屬性值
*/
class Son extends Component {
  render() {
    return (
      <div>
        <h1 className="h1">Son組件</h1>

        <div className="d-flex flex-column">
          <div className="btns fs-3 text-center  w-50 d-flex justify-content-around">
           {/*  <div className="w-25 bg-danger">我的</div>
            <div className="w-25">收藏</div>
            <div className="w-25">設(shè)置</div> */}

            {
              this.props.tabsProps.map( tab => (
                <div className={'w-25 '+(tab.isActive ? 'bg-danger': '')} key={tab.tid} onClick={this.selecteItem.bind(this, tab.tid)}>{tab.title}</div>
              ) )
            }
          </div>
          <div className="content">
            {
              this.props.tabsProps.find( tab => tab.isActive ).title
            }
          </div>
        </div>
      </div>
    )
  }

  selecteItem(selectedID){
    console.log('選擇tab id=>', selectedID);
    this.props.changeItem(selectedID);
  }
}

export default Son

練習(xí)三:

props 數(shù)據(jù)類型校驗(yàn) 寫法有兩種:

1、在當(dāng)前的類中定義 一個(gè)靜態(tài)變量 ?static propTypes(該變量名稱不允許隨意修改)

2、在當(dāng)前的類之外 定義一個(gè)靜態(tài)變量 ?類名.propTypes(該變量名稱不允許隨意修改)

Father:

import { Component } from 'react';

import Son from './Son'

/* 
props 數(shù)據(jù)類型檢測(cè)
*/

class Father extends Component {

  state = {
    num: 100,
    msg: 'Hello',
    arr: [],
    isFlag: true
  }
  render() {
    const { num ,msg, arr, isFlag } = this.state;
    return (
      <div>
        <h1>Father:</h1>
        <hr/>
        <Son pnum={num} pmsg={msg}  pisFlag={isFlag}/>
      </div>
    )
  }
}

export default Father

Son:

import React, { Component } from 'react';

import FatherPropTypes from 'prop-types';


class Son extends Component {

  /* static propTypes = {
    pnum: FatherPropTypes.number, //數(shù)據(jù)類型 number
    pmsg: FatherPropTypes.string,
    parr: FatherPropTypes.array.isRequired, //必填屬性
    pisFlag: FatherPropTypes.bool
  } */

  render() {
    const {pnum, pmsg, parr, pisFlag} = this.props;
    return (
      <div>
        <h1>Son:</h1>
        <h6>pnum:{pnum}</h6>
        <h6>pmsg:{pmsg}</h6>
        <h6>parr:{parr}</h6>
        <h6>pisFlag:{pisFlag}</h6>
      </div>
    )
  }
}

Son.propTypes = {
  pnum: FatherPropTypes.number, //數(shù)據(jù)類型 number
  pmsg: FatherPropTypes.string,
  parr: FatherPropTypes.array.isRequired, //必填屬性
  pisFlag: FatherPropTypes.bool
}


export default Son;

練習(xí)四:

props 默認(rèn)值設(shè)置 寫法有兩種:

1、在當(dāng)前的類中定義 一個(gè)靜態(tài)變量 ?static defaultProps(該變量名稱不允許隨意修改)

2、在當(dāng)前的類之外 定義一個(gè)靜態(tài)變量 ?類名.defaultProps(該變量名稱不允許隨意修改)

什么時(shí)候調(diào)用默認(rèn)值:

1、傳遞的prop 原本的值為 undefined 則調(diào)用 默認(rèn)值

2、沒(méi)有傳遞 prop 則調(diào)用 默認(rèn)值文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-715505.html

Father:

import { Component } from 'react';

import Son from './Son'

/* 
props 默認(rèn)值設(shè)置
*/

class Father extends Component {

  state = {
    num: undefined,
    msg: undefined,
    arr: undefined,
    isFlag: undefined
  }
  render() {
    const { num ,msg, arr, isFlag } = this.state;
    return (
      <div>
        <h1>Father:</h1>
        <hr/>
        <Son pnum={num} pmsg={msg} parr={arr} pisFlag={isFlag}/>
      </div>
    )
  }
}

export default Father

Son:

import React, { Component } from 'react';



class Son extends Component {

  /* static defaultProps = {
    pnum: -1,    //FatherPropTypes.number, //數(shù)據(jù)類型 number
    pmsg: '沒(méi)有文字',//FatherPropTypes.string,
    parr:  [-100, -200, -300],//FatherPropTypes.array.isRequired, //必填屬性
    pisFlag: false
  } */

  render() {
    const {pnum, pmsg, parr, pisFlag} = this.props;
    return (
      <div>
        <h1>Son:</h1>
        <h6>pnum:{pnum}</h6>
        <h6>pmsg:{pmsg}</h6>
        <h6>parr:{parr}</h6>
        <h6>pisFlag:{pisFlag}</h6>
      </div>
    )
  }
}

Son.defaultProps = {
  pnum: -1,    //FatherPropTypes.number, //數(shù)據(jù)類型 number
    pmsg: '沒(méi)有文字',//FatherPropTypes.string,
    parr:  [-100, -200, -300],//FatherPropTypes.array.isRequired, //必填屬性
    pisFlag: false
}


export default Son;

Son1:

import PropTypes from 'prop-types'
import { Component } from 'react'

/* 
props 進(jìn)行類型檢測(cè)與默認(rèn)值設(shè)置
*/

class Son1 extends Component {
  static propTypes = {}

  static defaultProps = {}

  render() {
    return (
      <div>Son1</div>
    )
  }
}

export default Son1

到了這里,關(guān)于react 組件之間的通信(父子組件)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來(lái)自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • 微信小程序-父子組件之間的通信

    父子組件之間通信的3種方式: 屬性綁定 用于父組件向子組件的指定屬性設(shè)置數(shù)據(jù),僅能設(shè)置JSON兼容的數(shù)據(jù) 子組件在properties節(jié)點(diǎn)中聲明對(duì)應(yīng)的屬性并使用。代碼: 事件綁定 用于子組件向父組件傳遞數(shù)據(jù),可以傳遞任意數(shù)據(jù) 事件綁定用于實(shí)現(xiàn)子向父?jìng)髦担梢詡鬟f任意類型

    2024年02月03日
    瀏覽(87)
  • react父子組件通信

    父?jìng)髯樱鹤畛R?jiàn) 把父組件中的數(shù)據(jù)傳給子組件 子傳父:子組件調(diào)用父組件傳遞過(guò)來(lái)的參數(shù),并且把想要傳遞的數(shù)據(jù)當(dāng)成函數(shù)的實(shí)參傳入即可 【子組件通過(guò)調(diào)用父組件傳遞到子組件的方法向父組件傳遞數(shù)據(jù)】 對(duì)于子傳父中子組件還是先調(diào)用了父組件傳遞過(guò)來(lái)的參數(shù),之后再向

    2024年02月07日
    瀏覽(28)
  • 微信小程序父子組件之間通信的 3 種方式

    父子組件之間通信的 3 種方式 ① 屬性綁定 ? 用于父組件向子組件的指定屬性設(shè)置數(shù)據(jù),僅能設(shè)置 JSON 兼容的數(shù)據(jù) ② 事件綁定 ? 用于子組件向父組件傳遞數(shù)據(jù),可以傳遞任意數(shù)據(jù) ③ 獲取組件實(shí)例 ? 父組件還可以通過(guò) this.selectComponent() 獲取子組件實(shí)例對(duì)象,這樣就可以直

    2024年02月09日
    瀏覽(85)
  • 【react從入門到精通】React父子組件通信方式詳解(有示例)

    【react從入門到精通】React父子組件通信方式詳解(有示例)

    【分享幾個(gè)國(guó)內(nèi)免費(fèi)可用的ChatGPT鏡像】 【10幾個(gè)類ChatGPT國(guó)內(nèi)AI大模型】 【用《文心一言》1分鐘寫一篇博客簡(jiǎn)直yyds】 【用訊飛星火大模型1分鐘寫一個(gè)精美的PPT】 在上一篇文章《JSX詳解》中我們了解了什么是jsx以及jsx的語(yǔ)法規(guī)則。 本文中我們將詳細(xì)了解React父子組件通信方式

    2024年02月05日
    瀏覽(124)
  • 前端vue中父子組件之間的傳值(修改值)和事件的相互調(diào)用

    目錄 父組件向子組件傳值 子組件修改父組件中的值: 方法1 方法2 子組件調(diào)用父組件里的函數(shù) 方法1 方法2 父組件調(diào)用子組件的函數(shù) : 子組件中的 data 屬性是用來(lái)存儲(chǔ)子組件自身的數(shù)據(jù),而不是用來(lái)接收父組件傳遞的數(shù)據(jù)的。父組件向子組件傳遞數(shù)據(jù)的常用方式是通過(guò) pro

    2024年02月07日
    瀏覽(92)
  • React組件之間通信

    1-1、安裝 1-2、使用 A組件 B組件 1-3、總結(jié)

    2024年02月16日
    瀏覽(22)
  • 前端基礎(chǔ)(props emit slot 父子組件間通信)

    前端基礎(chǔ)(props emit slot 父子組件間通信)

    前言 :如何實(shí)現(xiàn)組件的靈活使用,今天學(xué)習(xí)組件封裝用到的props、slot和emit。 目錄 props 子組件 父組件 示例代碼 slot 示例代碼 作用域插槽 emit 示例代碼 需要實(shí)現(xiàn)在其他組件中使用同一個(gè)子組件。 子組件(所謂子組件,就是封裝好的組件,供其他組件使用) 子組件定義了so

    2024年02月11日
    瀏覽(100)
  • React中組件之間如何通信?

    React中組件之間如何通信?

    我們將組件間通信可以拆分為兩個(gè)詞: 組件 通信 回顧Vue系列的文章,組件是 vue 中最強(qiáng)大的功能之一,同樣組件化是 React 的核心思想 相比 vue , React 的組件更加靈活和多樣,按照不同的方式可以分成很多類型的組件 而通信指的是發(fā)送者通過(guò)某種媒體以某種格式來(lái)傳遞信息

    2024年02月04日
    瀏覽(16)
  • React中消息訂閱與發(fā)布(PubSubJS)——兩個(gè)組件之間通信

    React中消息訂閱與發(fā)布(PubSubJS)——兩個(gè)組件之間通信

    結(jié)合案例:github搜索案例 結(jié)果如下圖 1.父容器代碼 2.搜索Search子模塊代碼(發(fā)布消息) 3.展示Lisi子模塊代碼(訂閱消息) 發(fā)布訂閱分析 在Search子模塊中發(fā)布消息,用PubSub.publish中進(jìn)行發(fā)布消息,在List子模塊中訂閱消息,拿到數(shù)據(jù)進(jìn)行展示 使用步驟 工具庫(kù): PubSubJS 下載: npm instal

    2024年02月09日
    瀏覽(19)
  • 前端react入門day03-react獲取dom與組件通信

    前端react入門day03-react獲取dom與組件通信

    (創(chuàng)作不易,感謝有你,你的支持,就是我前行的最大動(dòng)力,如果看完對(duì)你有幫助,請(qǐng)留下您的足跡) 目錄 受控表單綁定? React中獲取DOM 組件通信 父?jìng)髯? 父?jìng)髯?基礎(chǔ)實(shí)現(xiàn) 父?jìng)髯?props說(shuō)明 父?jìng)髯?- 特殊的prop children 子傳父? 使用狀態(tài)提升實(shí)現(xiàn)兄弟組件通信 使用Context機(jī)制跨

    2024年02月01日
    瀏覽(23)

覺(jué)得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包