[英]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.Cell
是SU_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.