freeCodeCamp/curriculum/challenges/chinese/03-front-end-libraries/react/create-a-component-with-com...

3.4 KiB
Raw Blame History

id title challengeType isRequired videoUrl localeTitle
5a24c314108439a4d4036164 Create a Component with Composition 6 false 使用Composition创建一个Component

Description

现在我们来看看如何组合多个React组件。想象一下您正在构建一个应用程序并创建了三个组件一个Navbar DashboardFooter 。要将这些组件组合在一起,您可以创建一个App 组件,它将这三个组件中的每一个都呈现为组件。要在React组件中将组件呈现为子组件请在JSX中包含作为自定义HTML标记编写的组件名称。例如render方法中,您可以编写:
回来(
<应用>
<Navbar />
<仪表板/>
<页脚/>
</应用>
当React遇到引用另一个组件的自定义HTML标记在此示例中包含在< />的组件名称)时,它会在标记的位置呈现该组件的标记。这应该说明App组件与Navbar DashboardFooter之间的父/子关系。

Instructions

在代码编辑器中,有一个名为ChildComponent的简单功能组件和一个名为ParentComponent的React组件。通过在ParentComponent呈现ChildComponent将两者组合在一起。确保使用正斜杠关闭ChildComponent标记。 注意: ChildComponent是使用ES6箭头函数定义的因为这是使用React时非常常见的做法。但是要知道这只是一个功能。如果您不熟悉箭头函数语法请参阅JavaScript部分。

Tests

tests:
  - text: React组件应返回单个<code>div</code>元素。
    testString: 'assert((function() { var shallowRender = Enzyme.shallow(React.createElement(ParentComponent)); return shallowRender.type() === "div"; })(), "The React component should return a single <code>div</code> element.");'
  - text: 该组件应返回两个嵌套元素。
    testString: 'assert((function() { var shallowRender = Enzyme.shallow(React.createElement(ParentComponent)); return shallowRender.children().length === 2; })(), "The component should return two nested elements.");'
  - text: 该组件应将ChildComponent作为其第二个子项返回。
    testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ParentComponent)); return mockedComponent.find("ParentComponent").find("ChildComponent").length === 1; })(), "The component should return the ChildComponent as its second child.");'

Challenge Seed

const ChildComponent = () => {
  return (
    <div>
      <p>I am the child</p>
    </div>
  );
};

class ParentComponent extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div>
        <h1>I am the parent</h1>
        { /* change code below this line */ }


        { /* change code above this line */ }
      </div>
    );
  }
};

After Test

console.info('after the test');

Solution

// solution required