6.2 KiB
6.2 KiB
id, title, challengeType, isRequired, forumTopicId, localeTitle
id | title | challengeType | isRequired | forumTopicId | localeTitle |
---|---|---|---|---|---|
5a24c314108439a4d403616a | Pass an Array as Props | 6 | false | 301401 | Передайте массив как реквизит |
Description
props
или свойств. В этой задаче рассматривается, как массивы могут быть переданы в качестве props
. Чтобы передать массив элементу JSX, он должен рассматриваться как JavaScript и завернут в фигурные скобки. <ParentComponent>Затем дочерний компонент имеет доступ к
<Цвета ChildComponent = {["зеленый", "синий", "красный"]} />
</ ParentComponent>
colors
свойств массива. При доступе к свойству могут использоваться методы массива, такие как join()
. const ChildComponent = (props) => <p>{props.colors.join(', ')}</p>
Это объединит все элементы массива colors
в строку, разделенную запятой, и произведет: <p>green, blue, red</p>
Позже мы узнаем о других распространенных методах рендеринга массивов данных в React.
Instructions
List
и ToDo
. При рендеринге каждого List
из компонента ToDo
передайте свойство tasks
назначенное массиву заданий, например ["walk dog", "workout"]
. Затем войдите в этот массив tasks
в компоненте List
, показывая его значение в p
элементе. Используйте join(", ")
чтобы отобразить массив props.tasks
в элементе p
как список, разделенный запятыми. В сегодняшнем списке должно быть не менее двух задач, а завтра должно быть не менее 3 задач.
Tests
tests:
- text: The <code>ToDo</code> component should return a single outer <code>div</code>.
testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ToDo)); return mockedComponent.children().first().type() === 'div'; })());
- text: The third child of the <code>ToDo</code> component should be an instance of the <code>List</code> component.
testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ToDo)); return mockedComponent.children().first().childAt(2).name() === 'List'; })());
- text: The fifth child of the <code>ToDo</code> component should be an instance of the <code>List</code> component.
testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ToDo)); return mockedComponent.children().first().childAt(4).name() === 'List'; })());
- text: Both instances of the <code>List</code> component should have a property called <code>tasks</code> and <code>tasks</code> should be of type array.
testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ToDo)); return Array.isArray(mockedComponent.find('List').get(0).props.tasks) && Array.isArray(mockedComponent.find('List').get(1).props.tasks); })());
- text: The first <code>List</code> component representing the tasks for today should have 2 or more items.
testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ToDo)); return mockedComponent.find('List').get(0).props.tasks.length >= 2; })());
- text: The second <code>List</code> component representing the tasks for tomorrow should have 3 or more items.
testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ToDo)); return mockedComponent.find('List').get(1).props.tasks.length >= 3; })());
- text: The <code>List</code> component should render the value from the <code>tasks</code> prop in the <code>p</code> tag.
testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ToDo)); return mockedComponent.find('p').get(0).props.children === mockedComponent.find('List').get(0).props.tasks.join(', ') && mockedComponent.find('p').get(1).props.children === mockedComponent.find('List').get(1).props.tasks.join(', '); })());
Challenge Seed
const List = (props) => {
{ /* change code below this line */ }
return <p>{}</p>
{ /* change code above this line */ }
};
class ToDo extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<h1>To Do Lists</h1>
<h2>Today</h2>
{ /* change code below this line */ }
<List/>
<h2>Tomorrow</h2>
<List/>
{ /* change code above this line */ }
</div>
);
}
};
After Tests
ReactDOM.render(<ToDo />, document.getElementById('root'))
Solution
const List= (props) => {
return <p>{props.tasks.join(', ')}</p>
};
class ToDo extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<h1>To Do Lists</h1>
<h2>Today</h2>
<List tasks={['study', 'exercise']} />
<h2>Tomorrow</h2>
<List tasks={['call Sam', 'grocery shopping', 'order tickets']} />
</div>
);
}
};