【问题标题】:get component inside react-emotion or styled-component在 react-emotion 或 styled-component 中获取组件
【发布时间】:2018-07-03 01:02:10
【问题描述】:
import styled from 'react-emotion'

class Field extends React.Component<> {}

export default styled(Field)

如果我渲染这个组件并使用component.type,我会得到styled()... 函数而不是Field 组件。

我如何在样式函数中获得Field

【问题讨论】:

  • .type 甚至不适用于扩展 React.Component 的 Field 组件

标签: javascript reactjs styled-components emotion


【解决方案1】:

试试这个:

import styled from 'react-emotion'

const Field = ({ className }) => (
    <div className={className}>Some field</div>
)

const theField = styled(Field)`
    color: green;
`
export default theField 

【讨论】:

  • 这个问题有悬赏还是只是我的想象?
【解决方案2】:

导出函数只是导出函数,但我认为你想要组件。那为什么不呢?

import styled from 'react-emotion'

class Field extends React.Component<> {}

const styledField = styled(Field)

export default styledField

【讨论】:

  • 这个问题有悬赏还是只是我的想象?
  • 我认为是,但据我所知,它们会在 7 天左右后过期
  • 是的,但不应该分配给任何人,我看没有人得到它,这是如何避免的?
  • 据我所知,如果您不将答案标记为答案,那么没有人会得到它......
【解决方案3】:

styled 库不提供任何获取字段的方法。即使是 Field.type 也会是 undefined,因为 Field 没有这个属性。你可以试试这段代码看看:

 class Field extends React.Component<> {
  render() {
    return (<div></div>);
  }
}

console.log(Field.type); // this will be 'undefined' not 'div' as you might expect

【讨论】:

    猜你喜欢
    • 2020-11-07
    • 2022-08-19
    • 2019-05-11
    • 2020-06-09
    • 2018-12-14
    • 2019-07-28
    • 2020-05-20
    • 2021-12-08
    • 2022-11-29
    相关资源
    最近更新 更多