【问题标题】:Necessary to `import React from 'react'` when using styled-components?使用 styled-components 时是否需要从“react”导入 React?
【发布时间】:2018-06-23 14:24:27
【问题描述】:

如果我有一个纯组件,它只需要一些 props 并返回一些由 100% 使用 styled-components 创建的组件组成的 jsx,是否有必要 import React from 'react'

我收到 eslint 错误:react/react-in-jsx-scope,因为目前我没有导入 React from 'react',但我的代码仍然可以正常工作。这个原因让我怀疑我是否应该在这里导入 React。

这是我的纯组件文件的一个非常基本的示例:

import styled from 'styled-components'

// pure function
const Block = props => {
  return (
    <BlockOuter>
      <BlockInner>{props.children}</BlockInner>
    </BlockOuter>
  )
}

// styled component
const BlockOuter = styled.div`
  display: flex;
  flex-direction: column;
  border: 1px solid #f2f2f2;
  height: ${props => props.height || 400}px;
  width: ${props => props.width}px;
`

// styled component
const BlockInner = styled.div`
  overflow: auto;
`

【问题讨论】:

  • 因为 react v16 你不必导入它。我猜 eslint 并没有跟上这个变化。
  • @Sagivb.g 你有那个更新的更新日志的链接吗?
  • 不是很清楚,但是既然你can return a string or fragments那么像这样的无状态组件,将与任何其他正常功能一样,不是吗?并且有 this statement in their docs 关于 ESLINT 升级所需的信息。我记得在某处读过它,但现在找不到。但至于您的示例,我认为您应该导入 react 以支持 jsx。

标签: javascript reactjs ecmascript-6 styled-components


【解决方案1】:

自从 React V16 you can return a string from your components.
因此在某些情况下,返回字符串的无状态组件将与任何其他组件一样:

export const Hello = ({ name }) => `${name}`;

这里不需要react
当然,当您使用JSX 时,您将需要react

Here is a small example to demonstrate it
我没有使用 stack-sn-p,因为它不支持文件结构。

As for the eslint,我猜它不是 up to date 与当前版本的 react。

【讨论】:

  • 我想归根结底,它实际上只是一个导致我困惑的 eslint 规则。代码仍然可以正常工作,而且我相信使用样式组件不需要导入 React,因为它们从您那里抽象出 React,因此库实际上已经在使用它。
  • 另外,我不认为返回字符串只是为了满足 linting 规则。我将继续导入它。
猜你喜欢
  • 2017-06-17
  • 2021-01-09
  • 2019-02-18
  • 1970-01-01
  • 2018-04-14
  • 2021-08-07
  • 2019-03-03
  • 2021-07-15
  • 2021-12-27
相关资源
最近更新 更多