简体   繁体   中英

Why do you use reactjs children props?

App.js

import Header from "./header";
export default function App() {
  return (
    <div className="App">
      <Header />
    </div>
  );
}

Header.js

const Header = () => {
  return (
    <div>
      <h1>Hello World</h1>
    </div>
  );
};
export default Header;

The code that was applied using "children props"

App.js

import Header from "./header";
export default function App() {
  return (
    <div className="App">
      <Header>
        <h1>Hello World</h1>
      </Header>
    </div>
  );
}

Header.js

const Header = ({children}) => {
  return (
    <div>
      {children}
    </div>
  );
};
export default Header;

I think I can just make it using 'props', so what is the reason for using 'children props'?

props.children is a special prop, automatically passed to every component, that can be used to render the content included between the opening and closing tags when invoking a component. You can code it like this

const Header = (props) => {
  return <div>{props.children}</div>;
};

or

const Header = ({children}) => {
  return <div>{children}</div>;
};

This might be helpful: https://codeburst.io/a-complete-guide-to-props-children-in-react-c315fab74e7c

We sometimes use props or children to pass in values of strings, integers, boolean or etc. This helps to reduce the number of lines in one file and to make your code more readable.

The most important element is that you can reuse this component in your project. Reusability components save you time and extra lines of code.

I usually create reusable components for buttons, layouts, displays, Image Slider and etc. Below is the sample taken from you, but I've added children as props to accept any children's attributes.

const Header = ({children}) => {
  return (
    <div>
      {children}
    </div>
  );
};
export default Header;

This pattern of HTML is very familiar to us.

<select>
  <option value="a">a</option>
  <option value="b">b</option>
  <option value="c">c</option>
</select>

The thing is, this pattern shows the hierarchy of our components. In the same way in React, you can expose your component's hierarchy by children .

const Header = ({children}) => {
  return (
    <div>
      {children}
    </div>
  );
};
export default Header;

You can paint the same HTML with props of course, but this way is more declarative . As you can assume that anything wrapped by Header component will treat as children .

One more advantage of using children is that it can give you more reusability. You can find more information about composition in the official document .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM