温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

react中如何使用props实现父子组件通讯

发布时间:2022-04-19 17:45:56 来源:亿速云 阅读:186 作者:zzz 栏目:大数据

这篇文章主要介绍“react中如何使用props实现父子组件通讯”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“react中如何使用props实现父子组件通讯”文章能帮助大家解决问题。

实现父子组件双向数据流整体的思路是:

1,父组件可以向子组件传递props,props中带有初始化子组件的数据,还有回调函数

2,子组件的state发生变化时,在子组件的事件处理函数中,手动触发父函数传递进来的回调函数,同时时将子组件的数据传递回去(有时间研究)

父组件

父组件中定义一个函数,包含一个props的参数,函数内利用super(props)传递给子组件,this.state中用于定义本页面中要用到的以及要传递给子组件的变量。

父组件的render函数中利用<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)

子组件调用父组个传递过来的参数,并进行传值

import React from 'react';

function table(props) {
 console.log(props);
 return (
  <div className="table_main">
   <table>
     <tbody>
       <tr className="first_tr">
        <td>内容</td>
        <td>发起人</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实现父子组件通讯”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注亿速云行业资讯频道,小编每天都会为大家更新不同的知识点。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI