• react 嵌套组件的通信


    在react中经常会用到的组件嵌套,如下:

    图中 parent本身是一个自定义的组件,然后内部又加入了 child的自定义组件,那么这种情况,父子之间如何通信

    react中在父组件里面有一个 this.props.children  当没有子组件时,值为 undefined ,只有一个子组件时,为一个对象,多个子组件时为一个数组

    我们可以使用react提供的方法遍历子组件,并且绑定

    代码如下:

    child.jsx

    import React, { Component } from 'react';
    
    
    
    
    
    class Child extends Component {
    	constructor(props){
    		super(props);
        	this.state = {date: new Date()};
      }
      showValue=()=>{
        this.props.showValue && this.props.showValue()
      }
      render() {
        return (
          <div className="Child">
           	<div className="content">
               Child
               <button onClick={this.showValue}>调用父的方法</button>
           	</div>
          </div>
        );
      }
    }
    
    export default Child;
    

      

    在 parent.jsx中

    import React, { Component } from 'react';
    
    
    class Parent extends Component {
    	constructor(props){
    		super(props);
        	this.state = {date: new Date()};
      }
      showValue=()=>{
        console.log("showValue....")
      }
      renderChildren(props) {
        //遍历所有子组件
        return React.Children.map(this.props.children, child => {
            var childProps = {
              //把父组件的props.name赋值给每个子组件(父组件传值给子组件)
              name: props.name,
              //父组件的方法挂载到props.showValue上,以便子组件内部通过props调用
              showValue:this.showValue
            };
            return React.cloneElement(child,childProps );
        });
      }
      render() {
        return (
          <div className="Parent">
           	<div className="content">
               Parent
               {this.renderChildren(this.props)}
           	</div>
          </div>
        );
      }
    }
    
    export default Parent;
    

      

    关键在于:遍历内部的子组件,然后动态的给子组件绑定props

  • 相关阅读:
    单例
    ASIHttpRequest加载网络数据和上传数据功能
    JSONModel
    KVC/KVO
    C中的动态内存分配和释放(free)
    IOS开发中Xcode一些使用技巧,快捷键的使用
    Struts2文件上传
    Struts2的输入校验
    struts2类型转换中的错误处理
    struts2自定义类型转换器
  • 原文地址:https://www.cnblogs.com/muamaker/p/9640442.html
Copyright © 2020-2023  润新知