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

参考文档: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>
            

我是父亲容器

{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> "abc"}/> div> ) , document.getElementById('J_contentContainer'))

你可能感兴趣的:(react)