Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
411 views
in Technique[技术] by (71.8m points)

javascript - Reach Understanding Higher Order Component syntax

I am trying to understand the basic syntax of a React HOC. Consider below example;

//WithLoading.js
import React from 'react';
function WithLoading(Component) {
  return function WithLoadingComponent({ isLoading, ...props }) {
    if (!isLoading) return <Component {...props} />;
    return <p>Hold on, fetching data might take some time.</p>;
  };
}
export default WithLoading;

And it is invoked/used as below;

const ListWithLoading = WithLoading(List);

render() {
return (
  <ListWithLoading
    isLoading={this.state.loading}
    repos={this.state.repos}
  />
);

}

Now my specific question is - When we invoke the function WithLoading(), it actually returning an inner function (WithLoadingComponent). So if the returned thing i.e. ListWithLoading is a function and not a component, how are we able to use it as a component i.e.

<ListWithLoading
        isLoading={this.state.loading}
        repos={this.state.repos}
      />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The simplest way to define a component is to write a JavaScript function:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

This function is a valid React component because it accepts a single “props” (which stands for properties) object argument with data and returns a React element. We call such components “function components” because they are literally JavaScript functions.

And this is how we use it:

<Welcome name="Sara" />;

Isn't that the same ?) As long as your inner function returns "valid React stuff" it is a valid “function component”.

// ListWithLoading is just a reference, 
// to a function [function WithLoadingComponent(...) {}] which 
// is valid react component (same like function Welcome(...) {}),
// that is why you can use it like <ListWithLoading />
const ListWithLoading = WithLoading(List);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...