简体   繁体   中英

Is there anyway to spread the return of a function call into props in jsx?

I can't come up with a way to do it, but what I want is:

<ColumnDef key="label" ...createCommonColumnProps.call(this, {somestuff}) />
<ColumnDef key="count" ...createCommonColumnProps.call(this, {someOtherStuff}) />
<ColumnDef key="value" ...createCommonColumnProps.call(this, {yetOtherstuff}) />

I'm hoping it stupidly simple and I'm just being an idiot, but I can't find a way to do it without creating variables like

<ColumnDef key="label" {...column1} />
<ColumnDef key="count" {...column2} />
<ColumnDef key="value" {...column3} />

There are about 5 props, some of which are affected by the object passed to the function.

When I'm trying this in the chrome devtools console (just the js part, not the jsx part), I'm seeing things like this:

> function a() {
   return {a:1, b:2}
 }
undefined
> y = {... a()}
VM341:1 Uncaught SyntaxError: Unexpected token ...
> x = ... a()
VM368:1 Uncaught SyntaxError: Unexpected token ...
> x = {a:1,b:2}
Object {a: 1, b: 2}
> y = {...x}
VM888:1 Uncaught SyntaxError: Unexpected token ...

The JSX object expansion syntax looks like:

{...<expression>}

Where expression returns a reference to an object.

So in your case it would be

<ColumnDef key="label" {... createCommonColumnProps.call(this, {somestuff})} />

UPD to reflect your question update:

When I'm trying this in the chrome devtools console (just the js part, not the jsx part), I'm seeing things like this:

That's happening because even though JSX object spread syntax is looking similar to the non standardised yet ES object spread syntax - they are not interchangeable (and the chrome does not support the latter yet).

So, just use it exactly as I demonstrated in the example above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM