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

标签 javascript css reactjs

我正在尝试使用展开运算符来影响 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/

相关文章:

javascript - 如何使用jquery中的上传字段 "name"属性获取上传文件名

javascript - 如何在 angular.js 中动态应用自定义过滤器?

css - 如何停止:before element to push label text to the right

jquery - 跨度包装跨度

javascript - 在 react 中创建一个计时器

node.js - 在 Node v13 中使用 @babel/register 来创建 React 应用程序

javascript - AmCharts - 代码版本?

javascript - 在 AngularJS 中 setTimeout 之前显示标签

javascript - 可在特定的 div 内拖动

javascript - 如何在 React 上获取动态引用