Clone functional components in React
P粉851401475
P粉851401475 2023-09-10 17:44:34
0
1
379

I'm trying to modify and clone the child elements of a component I'm creating and recently noticed that mychildrentype changes depending on how I passchildren>.

For example, if I pass JSX as a child:

 
Hello

When I inspect thechildrenstructure inMyComponent, I can see the object as follows:

{ '$$typeof': Symbol(react.element), type: 'div', key: null, ref: null, props: { children: 'hello' }, _owner: null, _store: {} }

Sinceprops.childrenexists,React.cloneElementcan use it directly.

If I create a functional component like this:

const Hello: React.FC = () => 
hello
;

and try to use it like this:

  

Then the structure of thechildrenobject becomes like this:

{ '$$typeof': Symbol(react.element), type: [Function: Hello], key: null, ref: null, props: {}, _owner: null, _store: {} }

I can no longer useReact.cloneElementunless I callchildren.type(), but I can't find much documentation on that.

Why does this happen? Is this expected? Is callingchildren.type()the only way to clone the entire tree of children?

P粉851401475
P粉851401475

reply all (1)
P粉744691205

Hello
is a div and is a function that returns a div, so obviously they are not the same thing. There is an empty object as propsbecause it has no child objects and we are not passing it a property with a value, so propsis {}.

What you really want to access and clone are the child elements of the parent JSX element returned, regardless of their props.
The parent JSX element returned is actuallychildren.type()(what the function returns) which has the children wrapped in it (Hello), sochildren.type().props.children is also present here so you can clone it.

    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!