抹桥的博客
Language
Home
Archive
About
GitHub
Language
主题色
250
196 words
1 minutes
React Source Code Explained: `onlyChildren`

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.

Related Articles#

  • {% 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 %}

This article was published on September 21, 2017 and last updated on September 21, 2017, 2937 days ago. The content may be outdated.

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
License
CC BY-NC-ND 4.0