react 父子组件之间通讯props
实现父子组件双向数据流整体的思路是:
1,父组件可以向子组件传递props,props中带有初始化子组件的数据,还有回调函数
2,子组件的state发生变化时,在子组件的事件处理函数中,手动触发父函数传递进来的回调函数,同时时将子组件的数据传递回去(有时间研究)
父组件
父组件中定义一个函数,包含一个props的参数,函数内利用super(props)传递给子组件,this.state中用于定义本页面中要用到的以及要传递给子组件的变量。
父组件的render函数中利用
(ps:此例子中也包含组件之间的嵌套,同时组件的名称开头字母必须大写,不然会报错)
importReactfrom'react'; importFooterfrom'./footer.js' importTablefrom'./table.js' classpagedemoextendsReact.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(){ letlist=this.state.list; return(//组件之间的通讯
子组件(table.js)
子组件调用父组个传递过来的参数,并进行传值
importReactfrom'react'; functiontable(props){ console.log(props); return(
内容 发起人 类型 时间 操作 { props.list.map(function(name){//接受父组件传递过来的值并进行处理 return({name.title} {name.person} {name.type} {name.time} {name.operation} ) }) }