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

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

当前回答

这是回答,但想添加一个优化示例。您可以内联分解以只获得特定的属性,而不是整个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>

其他回答

这是回答,但想添加一个优化示例。您可以内联分解以只获得特定的属性,而不是整个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组件的渲染方法中看到了这一点,就像这样(编辑:你编辑的问题确实显示了这一点):

class Example extends React.Component { render() { return <div> <div>Children ({this.props.children.length}):</div> {this.props.children} </div>; } } class Widget extends React.Component { render() { return <div> <div>First <code>Example</code>:</div> <Example> <div>1</div> <div>2</div> <div>3</div> </Example> <div>Second <code>Example</code> with different children:</div> <Example> <div>A</div> <div>B</div> </Example> </div>; } } ReactDOM.render( <Widget/>, document.getElementById("root") ); <div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

children是React组件的一个特殊属性,它包含组件中定义的任何子元素,例如上面Example中的div。{this.props。Children}在呈现的结果中包含这些子元素。

...在什么情况下使用相同的词

当你想在呈现的输出中直接包含子元素时,你可以这样做;如果你不这样做就不会。

道具。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>

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