React 克隆组件:React.cloneElement()

react提供了一个克隆 API:

React.cloneElement(
  element,
  [props],
  [...children]
)

官方定义:

Clone and return a new React element using element as the starting point. The resulting element will have the original element's props with the new props merged in shallowly. New children will replace existing children. key and ref from the original element will be preserved.

下面实现一个demo,通过 React.cloneElement 向子组件传递 state 及 function,代码如下:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class MyContainer extends Component {
    constructor(props) {
        super(props)
        this.state = {
            count: 1
        }
        this.handleClick = this.handleClick.bind(this);
    }

    handleClick() {
        this.state.count++;
        this.setState({
            count: this.state.count++
        })
        console.log(this.state)
    }

    render() {
        const childrenWithProps = React.Children.map(this.props.children, child => React.cloneElement(child, 
            {
                parentState: this.state.count,
                handleClick: this.handleClick
            }
        ));
        return (
            <div style={{border:"1px solid blue"}}>
                <span>父容器:</span>
                { childrenWithProps }
            </div>
        )
    }
}
class MySub extends Component {
    constructor(props) {
        super(props)
        this.state = {
            flag: false
        }
    }

    render() {
        return (
            <div style={{margin: "15px", border: "1px solid red"}}>
                子元素:{this.props.subInfo}
                <br/>
                父组件属性count值: { this.props.parentState }
                <br/>
                <span onClick={ () => this.props.handleClick() } 
                      style={{display:"inline-block",padding: "3px 5px", color:"#ffffff", background: "green", borderRadius: "3px", cursor: "pointer"}} 
                >click me</span>
            </div>
        )
    }
}
ReactDOM.render (
    (
        <MyContainer>
            <MySub subInfo={"1"}/>
            <MySub subInfo={"2"}/>
        </MyContainer>
    )
    , document.getElementById('content'))
    

<!DOCTYPE html>
<head>
    <meta charset="UTF-8">
    <title>react drag components example...</title>
    <link rel="stylesheet" href="/build/main.css">
</head>

<body>
    <div id="content"></div>
    <script src="bundle.js"></script>
</body>

</html>

需要注意,在父组件的构造器中,需要动态制定函数的 this 指向,否则该函数通过事件触发时,this指向子组件。通过下面语句:

this.handleClick = this.handleClick.bind(this);

效果如图:
图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值