首先写 2 个组件,打印一下他们的属性:

    const TextFunc = (props) => {        console.log('render TextFunc',props)        return <div>function</div>    }    class TextComponent extends React.Component {        render() {            console.log('render TextComponent', this.props)            return <div>class qwerty</div>        }    }

打印结果:

$$typeof: Symbol(react.element)key: nullprops: {}ref: nulltype: {        arguments: [Exception]        caller: [Exception]        length: 0        name: "TextFunc"        __proto__: ƒ ()    }_owner: null_store: {validated: false}_self: null_source: null__proto__: Object
$$typeof: Symbol(react.element)key: nullprops: {}ref: nulltype: {    class TextComponent    arguments: [Exception]    caller: [Exception]    length: 0    name: "TextComponent"    prototype: Component {constructor: ƒ, render: ƒ}    __proto__: ƒ Component(props, context, updater)}_owner: null_store: {validated: false}_self: null_source: null__proto__: Object

略微比较一下,可以发现 只有 type 是不一样的, 他指向的是 class 和 function

大家都知道:

<TextFunc/>

其实是一个语法糖,他的真实语法是这样的:

React.createElement(TextFunc)

关于 children 的打印:

<TextFunc>    <TextComponent/></TextFunc>
children:{    $$typeof: Symbol(react.element)    key: null    props: {}    ref: null    type: class TextComponent    _owner: null    _store: {validated: true}    _self: null    _source: null    __proto__: Object}// 或者是一个数组 

children 传递的也是一个 createElement 的结果

想要修改 children,传递值给他 ,可以使用一个比较 hack 的方法:

    const TextFunc = (props) => {        console.log('render TextFunc', props)        const {children} = props       const element = React.createElement(children.type, {            ...children.props,            ...{                q: 123            }        })        return <div>            function            <p>children:</p>            {                element            }        </div>    }

比较正统的方法:

    const TextFunc2 = (props) => {        console.log('render TextFunc', props)        const {children} = props        const element = React.cloneElement(children, {            ...children.props,            ...{                q: 1234            }        })        return <div>            function2            <p>children2:</p>            {                element            }        </div>    }

cloneElement 与 createElement 有点不一样, cloneElement接受的是一个元素,而createElement接受的是一个组件

React.cloneElement()几乎等同于:

<element.type {...element.props} {...props}>{children}</element.type>

但是,这也保留了组件的ref。这意味着当通过ref获取子节点时,你将不会意外地从你祖先节点上窃取它。相同的ref将添加到克隆后的新元素中。

不知道大家有没有分清组件元素的区别了, 简单的说
组件被调用就成了元素

相关代码:
https://github.com/Grewer/JsD...