我是否需要为无状态功能组件导入React? [英] Do I need to import React for stateless functional components?

查看:104
本文介绍了我是否需要为无状态功能组件导入React?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我周围(例如博客文章,代码)我看到了React无状态功能组件的代码,其中导入了 React ,即使它从未使用过。

All around me (e.g. blog posts, code) I see code for React stateless functional components in which React is imported even though it's never used.

import React, { PropTypes } from 'react';

function MyComponent({ foo, bar }) {
  ...
  return ...;
}

MyComponent.propTypes = { 
  foo: PropTypes.string.isRequired,
  bar: PropTypes.func.isRequired
}

export default MyComponent;

我认为无需导入 React 进入功能组件,并且一直认为它只是组件是类和不再需要时的遗迹。

I'd argue there is no need for importing React into functional components, and have been assuming it's just a vestige from when the components were classes and is no longer needed.

我也很惊讶我的linter不会抱怨未使用的导入(当我导入未使用的东西时通常会抱怨)。

I'm also suprised that my linter doesn't complain about the un-used import (it normally complains when I import something that isn't used).

是否有理由将 React 导入到我不知道的功能组件中?

Is there some reason to import React into functional components that I'm not aware of?

推荐答案

是的,有。 Babel将JSX转换为使用 React

Yes, there is. Babel transpiles JSX to use React:

<div></div>

收件人:

React.createElement("div", null);

因此您的JSX在内部被转换为使用 React.createElement 在纯JavaScript中, 使用 React 。请记住,JSX只是纯JavaScript的语法糖。如果您没有专门导入它,它将报告未定义 React

So your JSX is internally transpiled to use React.createElement in pure JavaScript, which does use React. Remember that JSX is just syntactic sugar over pure JavaScript. If you don't specifically import it, it will report that React isn't defined.

这篇关于我是否需要为无状态功能组件导入React?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆