简体   繁体   中英

Spreading return value of lamda function as props

I know my title is quite weird. but allow me explain this first.


const alter = (currentFloor: number) => {
        if (overallState.startFloor === '' || overallState.endFloor === '')
            return {}
        if (
            Number(overallState.startFloor) <= currentFloor &&
            Number(overallState.endFloor) >= currentFloor
        ) {
            return { selectedKey: overallState.state }
        }
        return {}
    }

/* ... */

return({
   randomArray.map((e,index)=>(
    <Dropdown 
      placeholder="placeholder"
      options={someoptions}
      {...alter(index)} // how does it works????
    />
))
})



I have a function which returns object have prop of fluent UI conditionally.

as you can see, function alter returns object or undefined. but still, it is function.

I never heard about I can spread function itself in curly braces.

These codes work as I intended. but I have no idea how it works.

Can you please ask me what happened in these codes? Thanks.

you can spread the return value of a function in curly braces. not function itself.

in this case, your function will run first and return an object. then that object will spread.

{...alter(index)} -> {...{ selectedKey: overallState.state } or {}} -> {selectedKey: overallState.state}

Hope you understand.

These are fundamendals of how react translates JSX to its own code. Basicaly if you write

    <Dropdown 
      placeholder="placeholder"
      options={someoptions}
    />

Jsx will be translated to something like

React.createElement('Dropdown', {placeholder: "placeholder, options: someOptions})

if you use spread syntax like in your code

  <Dropdown 
      placeholder="placeholder"
      options={someoptions}
      {...alter(index)} // how does it works????
    />

it will be same as

React.createElement('Dropdown', {placeholder: "placeholder", options: someOptions, ...alter(index)})

and this works, because alter(index) function is called, which javascript simply see as given returned object which can be something like { selectedKey: overallState.state } whis is the same as

React.createElement('Dropdown', {placeholder: "placeholder", options: someOptions, ...{ selectedKey: overallState.state }})

which becomes

React.createElement('Dropdown', {placeholder: "placeholder", options: someOptions, selectedKey: overallState.state })

and transformed back in JSX

 <Dropdown 
      placeholder="placeholder"
      options={someoptions}
      selectedKey={overallState.state}
    />

its work just like basic spread syntax of object in function parameters.

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