简体   繁体   English

使用扩展运算符更改React组件的样式?

[英]Using the spread operator to change the style of a React component?

I'm trying to use the spread operator to affect the style of a React component, but it doesn't appear to work... 我正在尝试使用传播运算符来影响React组件的样式,但它似乎无法正常工作...

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. 如果您的<SU_Table.Cell />组件希望使用名称正常的道具(例如样式),则此方法应该可行。 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 . 我真的不确定SU_Table.CellSU_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 然后,您需要在SU_Table.Cell内的实际Node元素上使用styleProps

const SU_Table.Cell = (props) => {
     return (<div style={props.styleProps}> </div>)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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