簡體   English   中英

使用擴展運算符更改React組件的樣式?

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

我正在嘗試使用傳播運算符來影響React組件的樣式,但它似乎無法正常工作...

const newProps = { ...this.props, color: 'red' };

return (
  <SU_Table.Cell {...newProps}>
    {this.props.children}
  </SU_Table.Cell>
);

誰能告訴我是否有可能以這種方式進行更改?

如果您的<SU_Table.Cell />組件希望使用名稱正常的道具(例如樣式),則此方法應該可行。 如果沒有,您在控制台中收到任何錯誤消息?

 // 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> </> ) } } 

我真的不確定SU_Table.CellSU_Table.Cell 但是也許嘗試一下?

const newProps = { ...this.props, color: 'red' };

return (
  <SU_Table.Cell styleProps={...newProps}>
    {this.props.children}
  </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