--- id: 5a24c314108439a4d4036164 title: Create a Component with Composition challengeType: 6 isRequired: false videoUrl: '' localeTitle: 使用Composition创建一个Component --- ## Description
现在我们来看看如何组合多个React组件。想象一下,您正在构建一个应用程序并创建了三个组件,一个NavbarDashboardFooter 。要将这些组件组合在一起,您可以创建一个App 组件,它将这三个组件中的每一个都呈现为组件。要在React组件中将组件呈现为子组件,请在JSX中包含作为自定义HTML标记编写的组件名称。例如,在render方法中,您可以编写:
回来(
<应用>
<Navbar />
<仪表板/>
<页脚/>
</应用>
当React遇到引用另一个组件的自定义HTML标记(在此示例中包含在< />的组件名称)时,它会在标记的位置呈现该组件的标记。这应该说明App组件与NavbarDashboardFooter之间的父/子关系。
## Instructions
在代码编辑器中,有一个名为ChildComponent的简单功能组件和一个名为ParentComponent的React组件。通过在ParentComponent呈现ChildComponent将两者组合在一起。确保使用正斜杠关闭ChildComponent标记。 注意: ChildComponent是使用ES6箭头函数定义的,因为这是使用React时非常常见的做法。但是,要知道这只是一个功能。如果您不熟悉箭头函数语法,请参阅JavaScript部分。
## Tests
```yml tests: - text: React组件应返回单个div元素。 testString: 'assert((function() { var shallowRender = Enzyme.shallow(React.createElement(ParentComponent)); return shallowRender.type() === "div"; })(), "The React component should return a single div 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
```jsx const ChildComponent = () => { return (

I am the child

); }; class ParentComponent extends React.Component { constructor(props) { super(props); } render() { return (

I am the parent

{ /* change code below this line */ } { /* change code above this line */ }
); } }; ```
### After Test
```js console.info('after the test'); ```
## Solution
```js // solution required ```