--- id: 5a24c314108439a4d4036166 title: Compose React Components challengeType: 6 forumTopicId: 301381 localeTitle: 组合 React 组件 --- ## Description
随着挑战继续,我们将组合使用更复杂的 React 组件和 JSX,有一点需要注意。在其他组件中渲染 ES6 风格的类组件和渲染你在过去几个挑战中使用的简单组件没有什么不同。你可以在其他组件中渲染 JSX 元素、无状态功能组件和 ES6 类组件。
## Instructions
在代码编辑器中,TypesOfFood组件已经渲染了一个名为Vegetables的组件。此外,还有上次挑战中的Fruits组件。 在Fruits中嵌套两个组件,首先NonCitrus,然后是Citrus,这两个组件都是在后台为你提供的。接下来,将Fruits类组件嵌到TypesOfFood组件中,位于h1标题下方和Vegetables上方。结果应该是一系列嵌套的组件,它们使用两种不同的组件类型。
## Tests
```yml tests: - text: TypesOfFood组件应该返回单个div元素。 testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(TypesOfFood)); return mockedComponent.children().type() === 'div'; })()); - text: TypesOfFood组件应该返回Fruits组件。 testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(TypesOfFood)); return mockedComponent.children().childAt(1).name() === 'Fruits'; })()); - text: Fruits组件应该返回NonCitrus组件和Citrus组件。 testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(TypesOfFood)); return (mockedComponent.find('Fruits').children().find('NonCitrus').length === 1 && mockedComponent.find('Fruits').children().find('Citrus').length === 1); })()); - text: TypesOfFood组件应该返回Vegetables组件,且其位于Fruits组件之下。 testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(TypesOfFood)); return mockedComponent.children().childAt(2).name() === 'Vegetables'; })()); ```
## Challenge Seed
```jsx class Fruits extends React.Component { constructor(props) { super(props); } render() { return (

Fruits:

{ /* change code below this line */ } { /* change code above this line */ }
); } }; class TypesOfFood extends React.Component { constructor(props) { super(props); } render() { return (

Types of Food:

{ /* change code below this line */ } { /* change code above this line */ }
); } }; ```
### Before Test
```jsx class NonCitrus extends React.Component { render() { return (

Non-Citrus:

  • Apples
  • Blueberries
  • Strawberries
  • Bananas
); } }; class Citrus extends React.Component { render() { return (

Citrus:

  • Lemon
  • Lime
  • Orange
  • Grapefruit
); } }; class Vegetables extends React.Component { render() { return (

Vegetables:

  • Brussel Sprouts
  • Broccoli
  • Squash
); } }; ```
### After Test
```js ReactDOM.render(, document.getElementById('root')) ```
## Solution
```js class Fruits extends React.Component { constructor(props) { super(props); } render() { return (

Fruits:

{ /* change code below this line */ } { /* change code above this line */ }
) } } class TypesOfFood extends React.Component { constructor(props) { super(props); } render() { return (

Types of Food:

{ /* change code below this line */ } { /* change code above this line */ }
); } }; ```