React组件间通讯传值实现详解
作者:未及545
这篇文章主要介绍了React组件间通讯传值,react组件的通信属于开发基础知识,今天来梳理一下,当然rudex还按老规矩排除在外,如同上篇文章的hooks一样,单独梳理
组件的props:
1.组件是封闭的,要接收外部数据应该通过props来实现。
2.props的作用,接收传递给组件的数据。
3.传递数据:给组件标签添加属性
4.接收数据:函数组件通过参数props接收数据,类组件通过this.props接收数据。
特点:
1.可以给组件传递任意类型的数据。
2.props是只读对象,只能读取属性的值,不能修改对象。
3.使用类组件时,如果写了构造函数,应该将props传递给super(),否则无法在构造函数中获取props。
父->子传值
import React, { Component } from 'react'
import ComSmall from './ComSmall'
export default class ComBig extends Component {
  constructor(){
    super()
    this.state={
      info:"天冷了要加衣"
    }
  }
  render() {
    return (
      <div>我是父组件
        {/* 注册子组件 ,通过msg传递给子组件*/}
        <ComSmall msg={this.state.info}></ComSmall>
      </div>
    )
  }
}import React, { Component } from 'react'
export default class ComSmall extends Component {
  constructor(props){
    // 此处不传props
    super(props)
   this.state={ }
  //  console.log(this.props);此处打印的是undefined,传递后打印的是数据
  }
  render() {
    return (
      <div>我是子组件
        {/* 接收父组件传值 */}
        {this.props.msg}
      </div>
    )
  }
}子->父传值
利用回调函数,父组件提供回调,子组件调用,将要传递的数据作为回调函数的参数。
import React, { Component } from 'react'
export default class ComSmall extends Component {
  constructor(){ 
    super()
   this.state={
    msg:"给你买了一部手机"
   }
  }
  sendMsg(){
    // 子组件调用父组件传递过来的回调函数
    this.props.getMsg(this.state.msg)
  }
  render() {
    return (
      <div>我是子组件
    <button onClick={()=>this.sendMsg()}>给父组件传值</button>
      </div>
    )
  }
}import React, { Component } from 'react'
import ComSmall from './ComSmall'
export default class ComBig extends Component {
  constructor(){
    super()
    this.state={
     data:""
    }
  }
getChindMsg=(val)=>{
// console.log("获得子组件传过来的值:",val);
this.setState({
  data:val
})
} 
  render() {
    return (
      <div>我是父组件
        <p>获得子组件传过来的值:{this.state.data}</p>
        {/* 将回调函数传递给子组件 */}
        <ComSmall getMsg={this.getChindMsg}></ComSmall>
      </div>
    )
  }
}到此这篇关于React组件间通讯传值实现详解的文章就介绍到这了,更多相关React组件通讯传值内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
