作为React世界的初学者,我想深入了解当我使用{this.props时发生了什么。Children}和什么情况下使用相同。它在下面的代码片段的相关性是什么?

render() {
  if (this.props.appLoaded) {
    return (
      <div>
        <Header
          appName={this.props.appName}
          currentUser={this.props.currentUser}
        />
        {this.props.children}
      </div>
    );
  }
}

当前回答

对于子节点,有一个父节点,它是打开/关闭标签,就像在React的官方示例中看到的那样,即FancyBorder。

h1和p是FancyBorder的子元素。您可以通过CodePen链接在实践中检查它。

其他回答

Children是一个保留名称,这个特殊的子道具的值将始终是自定义组件的开始和结束标记之间的内容。 在这种情况下,这个开始和结束标签之间的内容,这是在那个组件内的子道具上可用的。

这是回答,但想添加一个优化示例。您可以内联分解以只获得特定的属性,而不是整个props对象(这意味着您不必一直编写props)。

const MyView = ({title, children}) => {
  return (
    <>
      <h1>{title}</h1>
      {children}
    </>
  );
}

然后你可以这样使用它:

import { MyView } from './MyView';

const MyParentView = () => {
  return (
    <MyView title="Hello">
      <h2>World</h2>
    </MyView>
  );
}

最终的结果将是HTML,呈现出如下内容:

<div>
  <h1>Hello</h1>
  <h2>World</h2>
</div>

对于子节点,有一个父节点,它是打开/关闭标签,就像在React的官方示例中看到的那样,即FancyBorder。

h1和p是FancyBorder的子元素。您可以通过CodePen链接在实践中检查它。

道具。Children表示调用/呈现组件时开始标记和结束标记之间的内容:

const Foo = props => (
  <div>
    <p>I'm {Foo.name}</p>
    <p>abc is: {props.abc}</p>

    <p>I have {props.children.length} children.</p>
    <p>They are: {props.children}.</p>
    <p>{Array.isArray(props.children) ? 'My kids are an array.' : ''}</p>
  </div>
);

const Baz = () => <span>{Baz.name} and</span>;
const Bar = () => <span> {Bar.name}</span>;

invoke /电话/ Foo负责:

<Foo abc={123}>
  <Baz />
  <Bar />
</Foo>

What even is ‘children’? The React docs say that you can use props.children on components that represent ‘generic boxes’ and that don’t know their children ahead of time. For me, that didn’t really clear things up. I’m sure for some, that definition makes perfect sense but it didn’t for me. My simple explanation of what this.props.children does is that it is used to display whatever you include between the opening and closing tags when invoking a component. A simple example: Here’s an example of a stateless function that is used to create a component. Again, since this is a function, there is no this keyword so just use props.children

const Picture = (props) => {
  return (
    <div>
      <img src={props.src}/>
      {props.children}
    </div>
  )
}

这个组件包含一个<img>,它接收一些道具,然后显示{props.children}。 每当调用此组件时{props。Children}也将被显示,这只是对组件开始和结束标记之间内容的引用。

//App.js
render () {
  return (
    <div className='container'>
      <Picture key={picture.id} src={picture.src}>
          //what is placed here is passed as props.children  
      </Picture>
    </div>
  )
}

而不是调用一个自结束标签<Picture />,如果你调用它将完整的开始和结束标签<Picture> </Picture>,然后你可以在它之间放置更多的代码。 这将<Picture>组件与其内容解耦,使其更具可重用性。

参考:React的props.children的简单介绍