react 父子組件之間通訊props
實現(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;
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
關(guān)于React Native報Cannot initialize a parameter of type''NSArra
這篇文章主要介紹了關(guān)于React Native報Cannot initialize a parameter of type'NSArray<id<RCTBridgeModule>>錯誤,本文給大家分享解決方案,需要的朋友可以參考下2021-05-05React 中常用的幾種路由跳轉(zhuǎn)方式小結(jié)
基本路由跳轉(zhuǎn)是最常見的一種方式,下面介紹React 中常用的幾種路由跳轉(zhuǎn)方式,感興趣的朋友一起看看吧2023-12-12reactjs學習解決unknown at rule @tailwind css
這篇文章主要介紹了reactjs學習解決unknown at rule @tailwind css問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02react如何使用useRef模仿抖音標題里面添加標簽內(nèi)容
本文介紹了如何模仿抖音發(fā)布頁面,使用div元素作為輸入框,并利用CSS樣式和JavaScript動態(tài)操作DOM,實現(xiàn)類似于input輸入框的功能,感興趣的朋友跟隨小編一起看看吧2024-10-10詳解Stack?Navigator中使用自定義的Render?Callback
這篇文章主要為大家介紹了Stack?Navigator中使用自定義的Render?Callback使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-10-10