I'm trying to use the spread operator to affect the style of a React component, but it doesn't appear to work...
const newProps = { ...this.props, color: 'red' };
return (
<SU_Table.Cell {...newProps}>
{this.props.children}
</SU_Table.Cell>
);
Can anyone tell me if it's possible to make the change in this way?
If your <SU_Table.Cell />
Component expects normal-named props (style for example) then this approach should work. if it doesn't is there any error messages you are receiving in your console?
// lets say "props" looks like this { fontSize: 12, children: [], somethingUnrelated: '@123123sadasd', text: 'Cell text' } class Table extends Component { render () { // the spreading of this.props will be applying unRelated properties to the Object // const newProps = { ...this.props, style: { color: 'red' } } // this spreading of this.props would also put the property 'children' into your // newProps Object and then ultimately into your SU_Table.Cell instantiation as an // attribute. // only taking what you want from props is more concise and readable. const { fontSize, text, children } = this.props const style = { fontSize, color: 'red' } const cellProps = { text, style } return ( <> <SU_Table.Cell {...cellProps}> {children} </SU_Table.Cell> //<SU_Table.Cell text="Cell text" style={{fontSize: 12, color: 'red'}}> // [] //</SU_Table.Cell> </> ) } }
I am really not sure what is SU_Table.Cell
. But maybe try this?
const newProps = { ...this.props, color: 'red' };
return (
<SU_Table.Cell styleProps={...newProps}>
{this.props.children}
</SU_Table.Cell>
);
And then you need to use styleProps
on the actual Node element inside SU_Table.Cell
const SU_Table.Cell = (props) => {
return (<div style={props.styleProps}> </div>)
}
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.