简体   繁体   中英

Passing object as props to jsx. Without {...obj}

I have an array from redux

let profiles = this.props.blocks.profiles.map(prof => {

    let arrayRows = {
        name: prof.name,
        version: prof.version,
        description: prof.description,
        community: prof.community
    }
    return (
        <MyComponent
            name={prof.name}
            custmProps
            custmProps
            custmProps
            {...arrayRows} // here I don't want this
        // I need object, which contains key-value from arrayRows
        />
    )

})

Because I want to create universal component, which can have 'n key-value prop with. So in MyComponent I have smt like this:

<myComponent>
    {this.props.title /* every component must have this */} 
    {this.props.id /* every component must have this */} 
    {this.props.arrayRows.map(arr => { 
        return (
            <BlockRow 
                blockRowName={arr.key} // here: name || version || description || community || ...
                blockRowVal={arr.val} // here: name.val || version.val || description.val || community.val || ...
            />
        )
    })}
</myComponent>

In Store I have array with objects. Each object have his own properties. This connection works fine

UPDATE

Reducer:

const initialState = { 
    profiles: [
        {
            id: '1',
            name: 'Profile 1',
            version: '23',
            description: 'description',
            community: 'community'
        },
        {
            id: '2',
            name: 'Profile 2',
            version: '23',
            description: 'description',
            community: 'community'
        }
    ]
}


const mapStateToProps = state => {
    return {
        blocks: state.myReducer
    };
};

Edit: you are doing a map twice What you are passing to your MyComponent is an element of your full array. Remove the map that's on this level. Pass the full array to MyComponent

return (
    <MyComponent
        name={prof.name}
        custmProps
        custmProps
        custmProps
        arrayRows={this.props.blocks.profiles} // here you want this
    />
)

You can just pass down an entire object as props as you would any other prop:

<MyComponent
    rows={arrayRows}
/>

And access it like this:

const MyComponent = ({rows}) => {
    console.log(rows);

    return null;
} 

There is no need to de-structure it. You will still be able to access your key-value pairs this way.

The most ES6 way is: the object will have the same name as the prop, than:

return (
<MyComponent
    name={prof.name}
    custmProps
    custmProps
    custmProps
    arrayRows // here what you need
/>

)

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