通过React.cloneElement给所有子元素添加属性

前端之家收集整理的这篇文章主要介绍了通过React.cloneElement给所有子元素添加属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_404_1@

参考文档:https://facebook.github.io/react/docs/react-api.html#cloneelement

import React,{Component} from 'react';
import ReactDOM from 'react-dom';
import Perf from 'react-addons-perf' // ES6
class MyContainer extends Component {
    constructor(props) {
        super(props)
        this.state = {
            count: 1
        }
    }

    render() {
        const childrenWithProps = React.Children.map(this.props.children,(child) => React.cloneElement(child,{baseInfo: "def"}));
        return <div>
            <h1> 我是父亲容器</h1>
            {childrenWithProps}
        </div>
    }
}
class MySub extends Component {
    constructor(props) {
        super(props)
        this.state = {
            count: 1
        }
    }

    render() {
        return <div>
            {this.props.subInfo}我是子元素{this.props.baseInfo}
        </div>
    }
}
ReactDOM.render(
    (
        <div>
            <MyContainer >
                <MySub subInfo={"abc"}/>

            </MyContainer>

        </div>
    ),document.getElementById('J_contentContainer'))

猜你在找的React相关文章