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

来源:互联网 发布:mac os x 重装 超慢 编辑:程序博客网 时间:2024/05/17 06:42

参考文档: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' // ES6class 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'))
0 0