抹桥的博客
Language
Theme Color
250

React Source Code Explained: `onlyChildren`

Outline

Version scope: This article preserves React 16.0.0-beta.5 implementations and APIs from its publication period. It is a historical reading, not a current usage guide. Consult the current official documentation for new work.

The code for this module is very simple, just a dozen lines.

var ReactElement = require("ReactElement");

var invariant = require("fbjs/lib/invariant");
function onlyChild(children) {
  invariant(
    ReactElement.isValidElement(children),
    "React.Children.only expected to receive a single React element child.",
  );
  return children;
}

module.exports = onlyChild;

Its purpose is to check if the passed children is a valid React element; otherwise, it throws an error. The validation logic resides within the ReactElement module:

ReactElement.isValidElement = function (object) {
  return (
    typeof object === "object" &&
    object !== null &&
    object.$typeof === REACT_ELEMENT_TYPE
  );
};

Summary

So, at this point, we’ve covered all the APIs and modules provided by React itself. However, simply looking at React’s core code doesn’t really solve many problems. For instance, how are React Component lifecycles implemented? How does setState work? And how are React Components rendered into the browser? There are still many questions. I’ll continue to seek these answers given the opportunity.

  • {% post_link react-source-code-analyze-1 React Source Code Analysis - Entry File %}
  • {% post_link react-source-code-analyze-2 React Source Code Analysis - ReactBaseClasses %}
  • {% post_link react-source-code-analyze-3 React Source Code Analysis - ReactChildren %}
  • {% post_link react-source-code-analyze-4 React Source Code Analysis - ReactElement %}
  • {% post_link react-source-code-analyze-5 React Source Code Analysis - onlyChildren %}
React Source Code Explained: `onlyChildren`
https://blog.kisnows.com/en-US/2017/09/21/react-source-code-analyze-5/
Author
Kisnows
Published at
2017-09-21