我正在尝试使用展开运算符来影响 React 组件的样式,但它似乎不起作用...
const newProps = { ...this.props, color: 'red' };
return (
<SU_Table.Cell {...newProps}>
{this.props.children}
</SU_Table.Cell>
);
谁能告诉我是否可以用这种方式进行更改?
最佳答案
如果您的 <SU_Table.Cell />
组件需要正常命名的 Prop (例如样式),那么这种方法应该有效。如果没有,您是否在控制台中收到任何错误消息?
// 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>
</>
)
}
}
关于javascript - 使用扩展运算符更改 React 组件的样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55334867/