Is React.Component the default extension when exporting?

百般思念 提交于 2019-12-19 10:36:12

问题


I am looking through some React projects, and sometimes see-

export default () => {

But other times I see-

export default class Entry extends React.Component {.

Is there any difference between the two, viz. does export automatically extend React.Component? What is the best practice?


回答1:


The export default () => you see is a React 0.14+ "Functional Component".

It's a new more concise syntax for writing React components. Both it and the other syntax are fine.

These components behave just like a React class with only a render method defined. Since no component instance is created for a functional component, any ref added to one will evaluate to null. Functional components do not have lifecycle methods, but you can set .propTypes and .defaultProps as properties on the function.

Basically doing:

class MyComponent extends React.Component {
  render() {
    return <p>Hello</p>;
  }
}

Is the same as:

const MyComponent = () => <p>Hello</p>;

When used inside React component and passed to Render.




回答2:


The first one is a functional component. However the other code will export a regular class/React component.

For example

export default (withHistory, onUpdate) => {
    const history = new HashHistory;
  return (
    <Router history={history} onUpdate={onUpdate}>
      <Route path='/' component={Index} />
    </Router>
  );
};

Will compile (at least with Babel+webpack) to

...
var _reactRouterLibHashHistory = __webpack_require__(35);
var _reactRouterLibHashHistory2 = _interopRequireDefault(_reactRouterLibHashHistory);
exports['default'] = function (withHistory, onUpdate) {
      var history = new _reactRouterLibHashHistory2['default']();
      return React.createElement(
        _reactRouter.Router,
        { history: history, onUpdate: onUpdate },
        React.createElement(_reactRouter.Route, { path: '/', component: _routesIndex2['default'] })
      );
    };
module.exports = exports['default'];
...


来源:https://stackoverflow.com/questions/34448901/is-react-component-the-default-extension-when-exporting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!