问题
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;
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.
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).
Is there some reason to import React into functional components that I'm not aware of?
回答1:
Yes, there is. Babel transpiles JSX to use React:
<div></div>
To:
React.createElement("div", null);
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.
回答2:
What exactly a React Stateless Functional Component is?
When you write a stateful component it has basic these three parts (other than all the logic):
1. constructor
2. lifecycle methods
3. render
And react convert this render part into:
React.createElement(element, null); //element will be the wrapper of all the jsx
Now when you write a Stateless Functional Component it basically has only a render part no constructor, no lifecycle method. Whatever you return from this component will also get converted into:
React.createElement(element, null);
So that's why importing React is required. Always keep in mind that we write JSX not html, that will get transpiled by babel.
Check the DOC for React without JSX.
Check the converted version of a functional component by Babel.
Hope this will help you.
来源:https://stackoverflow.com/questions/44141010/do-i-need-to-import-react-for-stateless-functional-components