溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

react 中怎么使用props實現(xiàn)父子組件通訊

發(fā)布時間:2021-06-16 16:03:52 來源:億速云 閱讀:144 作者:Leah 欄目:web開發(fā)

本篇文章給大家分享的是有關react 中怎么使用props實現(xiàn)父子組件通訊,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

實現(xiàn)父子組件雙向數(shù)據(jù)流整體的思路是:

1,父組件可以向子組件傳遞props,props中帶有初始化子組件的數(shù)據(jù),還有回調(diào)函數(shù)

2,子組件的state發(fā)生變化時,在子組件的事件處理函數(shù)中,手動觸發(fā)父函數(shù)傳遞進來的回調(diào)函數(shù),同時時將子組件的數(shù)據(jù)傳遞回去(有時間研究)

父組件

父組件中定義一個函數(shù),包含一個props的參數(shù),函數(shù)內(nèi)利用super(props)傳遞給子組件,this.state中用于定義本頁面中要用到的以及要傳遞給子組件的變量。

父組件的render函數(shù)中利用<Table list={this.state.list}/>此種形式傳遞給子組件

(ps:此例子中也包含組件之間的嵌套,同時組件的名稱開頭字母必須大寫,不然會報錯)

import React from 'react';
import Footer from './footer.js'
import Table from './table.js'

class pagedemo extends React.Component {
 constructor(props) {
  super(props);
  this.state = {
   list: [{
    'id':'1',
    'title':'123',
    'time':'2017',
    'person':'cheny0815',
    'type':'type',
    'operation':'operation'
   },{
    'id':'2',
    'title':'456',
    'time':'2017',
    'person':'cheny0815',
    'type':'type',
    'operation':'operation'
   },{
    'id':'3',
    'title':'789',
    'time':'2017',
    'person':'cheny0815',
    'type':'type',
    'operation':'operation'
   }]
  }
 }
 render() {
  let list = this.state.list;
  return (
   <div className="content">
    <div className="content_main">
      <Table list={list}/> //組件之間的通訊
    </div>
    <Footer /> //組件嵌套
   </div>
  );
 }
}

export default pagedemo;

子組件(table.js)

子組件調(diào)用父組個傳遞過來的參數(shù),并進行傳值

import React from 'react';

function table(props) {
 console.log(props);
 return (
  <div className="table_main">
   <table>
     <tbody>
       <tr className="first_tr">
        <td>內(nèi)容</td>
        <td>發(fā)起人</td>
        <td>類型</td>
        <td>時間</td>
        <td>操作</td>
       </tr>
       {
        props.list.map(function(name){ //接受父組件傳遞過來的值并進行處理
         return (
           <tr key={name.id}>
            <td>{name.title}</td>
            <td>{name.person}</td>
            <td>{name.type}</td>
            <td>{name.time}</td>
            <td>{name.operation}</td>
           </tr>
         )
        })
       }
     </tbody>
   </table>
  </div>
 )
}

export default table;

以上就是react 中怎么使用props實現(xiàn)父子組件通訊,小編相信有部分知識點可能是我們?nèi)粘9ぷ鲿姷交蛴玫降摹OM隳芡ㄟ^這篇文章學到更多知識。更多詳情敬請關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI