實現(xiàn)父子組件雙向數(shù)據(jù)流整體的思路是:
1,父組件可以向子組件傳遞props,props中帶有初始化子組件的數(shù)據(jù),還有回調(diào)函數(shù)
2,子組件的state發(fā)生變化時,在子組件的事件處理函數(shù)中,手動觸發(fā)父函數(shù)傳遞進(jìn)來的回調(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ù),并進(jìn)行傳值
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){ //接受父組件傳遞過來的值并進(jìn)行處理 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)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點
疑難解答