Уроки React. Урок 2, Домашнее задание.
Category:
Давайте пробежимся по нашему домашнему заданию. Смысл использования React это создание компонентов из вашего функционала, т.е. дробление приложение на маленькие независимые части. В нашем случае комментарии нужно сделать отдельным компонентами. Также хорошей практикой считается иметь как можно больше stateless компонентов. К примеру в нашем случае это файл comment.js.
1 2 3 4 5 6 7 8 9 | import React, { PropTypes } from 'react' function Comment(props) { const { comment: { text, user } } = props return ( <div> <p>{text}</p> <b>by {user}</b> </div> |
1 2 3 4 | ) } export default Comment |
CommentList.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | import React, { Component, PropTypes } from 'react' import Comment from './Comment' class CommentList extends Component { state = { isOpen: false } render() { const { comments } = this.props if (!comments || !comments.length) return <h3>no comments yet</h3> const { isOpen } = this.state const commentItems = comments.map(comment => <li key = {comment.id}><Comment comment = {comment}/></li>) const body = isOpen ? <ul>{commentItems}</ul> : null const linkText = isOpen ? 'close comments' : 'show comments' return ( <div> <a href="#" onClick = {this.toggleOpen}>{linkText}</a> {body} </div> ) } toggleOpen = (ev) => { ev.preventDefault() this.setState({ isOpen: !this.state.isOpen }) } } export default CommentList |
Наш файл Articles.js претерпит следующие изменения
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import React, { Component } from 'react' import CommentList from './CommentList' //added class Article extends Component { state = { render() { const article = this.props.article //deleted // const { article } = this.props //deleted // const { article: { title, text } } = props //deleted const { article: { title, text, comments } } = this.props //added const { isOpen } = this.state const body = isOpen ? <section>{ article.text }</section> : null //deleted const body = isOpen ? <section>{ text } <CommentList comments = {comments} /></section> : null //added return ( <div> <h1 onClick = {this.toggleOpen}>{ article.title }</h1> //deleted <h1 onClick = {this.toggleOpen}>{ title }</h1> //added {body} </div> ) |
Так будет выглядеть код нашего домашнего задания. Можете скачать файл с обновленным проектом отсюда или просто его скопировать. Далее будем работать в нем.
We are looking forward to meeting you on our website soshace.com
Sign in \ Sign Up
Or use email\username to sign in
By Signing In \ Signing Up, you agree to our privacy policy