Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    Programming

    Уроки React. Урок 11. Pt.1.

    JavaScript

    Building a Pokedex with Next.js

    JavaScript

    AI in Recruitment: Cases and Trends

    Important Pages:
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Today's Picks:
    • Scaling Success: Monitoring Indexation of Programmatic SEO Content
    • Leveraging Influencers: Key Drivers in New Product Launches
    • How Privacy-First Marketing Will Transform the Industry Landscape
    • The Impact of Social Proof on Thought Leadership Marketing
    • Balancing Value-Driven Content and Promotional Messaging Strategies
    • Top Influencer Marketing Platforms to Explore in 2025
    • Emerging Trends in Marketing Automation and AI Tools for 2023
    • Strategies to Mitigate Duplicate Content in Programmatic SEO
    Thursday, December 11
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Soshace Digital Blog
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Services
    • SaaS & Tech

      Maximizing Efficiency: How SaaS Lowers IT Infrastructure Costs

      August 27, 2025

      Navigating Tomorrow: Innovations Shaping the Future of SaaS

      August 27, 2025

      Maximizing Impact: Strategies for SaaS & Technology Marketing

      August 27, 2025
    • AI & Automation

      Enhancing Customer Feedback Analysis Through AI Innovations

      August 27, 2025

      Navigating the Impact of AI on SEO and Search Rankings

      August 27, 2025

      5 Automation Hacks Every Home Service Business Needs to Know

      May 3, 2025
    • Finance & Fintech

      Critical Missteps in Finance Marketing: What to Avoid

      August 27, 2025

      Analyzing Future Fintech Marketing Trends: Insights Ahead

      August 27, 2025

      Navigating the Complex Landscape of Finance and Fintech Marketing

      August 27, 2025
    • Legal & Compliance

      Exploring Thought Leadership’s Impact on Legal Marketing

      August 27, 2025

      Maximizing LinkedIn: Strategies for Legal and Compliance Marketing

      August 27, 2025

      Why Transparency Matters in Legal Advertising Practices

      August 27, 2025
    • Medical Marketing

      Enhancing Online Reputation Management in Hospitals: A Guide

      August 27, 2025

      Analyzing Emerging Trends in Health and Medical Marketing

      August 27, 2025

      Exploring Innovative Content Ideas for Wellness Blogs and Clinics

      August 27, 2025
    • E-commerce & Retail

      Strategic Seasonal Campaign Concepts for Online and Retail Markets

      August 27, 2025

      Emerging Trends in E-commerce and Retail Marketing Strategies

      August 27, 2025

      Maximizing Revenue: The Advantages of Affiliate Marketing for E-Commerce

      August 27, 2025
    • Influencer & Community

      Leveraging Influencers: Key Drivers in New Product Launches

      August 27, 2025

      Top Influencer Marketing Platforms to Explore in 2025

      August 27, 2025

      Key Strategies for Successful Influencer Partnership Negotiations

      August 27, 2025
    • Content & Leadership

      The Impact of Social Proof on Thought Leadership Marketing

      August 27, 2025

      Balancing Value-Driven Content and Promotional Messaging Strategies

      August 27, 2025

      Analyzing Storytelling’s Impact on Content Marketing Effectiveness

      August 27, 2025
    • SEO & Analytics

      Scaling Success: Monitoring Indexation of Programmatic SEO Content

      August 27, 2025

      Strategies to Mitigate Duplicate Content in Programmatic SEO

      August 27, 2025

      Effective Data Visualization Techniques for SEO Reporting

      August 27, 2025
    • Marketing Trends

      How Privacy-First Marketing Will Transform the Industry Landscape

      August 27, 2025

      Emerging Trends in Marketing Automation and AI Tools for 2023

      August 27, 2025

      Maximizing ROI: Key Trends in Paid Social Advertising

      August 27, 2025
    Soshace Digital Blog
    Blog / Programming / Уроки React. Урок 4. Домашнее Задание.
    Programming

    Уроки React. Урок 4. Домашнее Задание.

    bragin_paBy bragin_paSeptember 14, 2016Updated:December 6, 2024No Comments3 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    Уроки React. Урок 4. Домашнее Задание.
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link

    a2a2543d-1502-4fac-9336-8f9627510105

    Поговорим о нашем домашнем задании. Стоит отметить что при разработке decorators/mixins вся логика в большинстве случаев работает прекрасно. Она была реализована нами в классе, для выполнения домашнего задания оставалось вынести ее в decorator и соответствующий mixin. Так будет выглядеть наш decorator (src/decorators/oneOpen.js):

    import React, { Component as ReactComponent} from 'react'
    
    export default (Component) => class OneOpen extends ReactComponent {
        state = {
            openItemId: null
        }
    
        openItem = openItemId => ev => {
            if (ev) ev.preventDefault()
            this.setState({ openItemId })
        }
    
        toggleOpenItem = id => ev => {
            if (ev) ev.preventDefault()
            this.setState({
                openItemId: id == this.state.openItemId ? null : id
            })
        }
    
        isItemOpen = id => this.state.openItemId == id
    
    
        render() {
            return <Component {...this.props} isItemOpen = {this.isItemOpen} openItem = {this.openItem} toggleOpenItem  = {this.toggleOpenItem}/>
        }
    }

    Decorators и mixins создаются для того чтобы вы могли переиспользовать ваш код, т.е. написав его однажды,применять его в разных местах. То что сегодня работает для статей завтра будет работать для комментариев, авторов и.т.п. Поэтому при присваивании имен вашим сущностям делайте более универсальные названия. К примеру: openItem, openElement. Для того чтобы сделать опциональную часть домашнего задания достаточно проверить когда нам приходит id, совпадает ли он с тем который у нас уже храниться в state. Если да, это означает что нам нужно закрыть статью, чтобы это сделать достаточно присвоить null, а иначе мы просто поменяем id:

    openItemId: id == this.state.openItemId ? null : id

    Наш mixin (src/mixins/oneOpen.js) будет выглядеть следующим образом:

    export default {
        getInitialState() {
            //this.props
            return {
                openItemId: false
            }
        },
        openItem(openItemId) {
            return ev => {
                if (ev) ev.preventDefault()
                this.setState({openItemId})
            }
        },
    
        toggleOpenItem(id) {
            return ev => {
                if (ev) ev.preventDefault()
                this.setState({
                    openItemId: id == this.state.openItemId ? null : id
                })
            }
        },
    
        isItemOpen(id) {
            return this.state.openItemId == id
        }
    }

    Также  ArticleList.js измениться следующим образом:

    import React, { Component }  from 'react'
    import Article from './Article'
    import oneOpen from './decorators/oneOpen'
    
    class ArticleList extends Component {
        render() {
            const { articles, isItemOpen, toggleOpenItem } = this.props
    
            const listItems = articles.map((article) => <li key={article.id}>
                <Article article = {article}
                    isOpen = {isItemOpen(article.id)}
                    openArticle = {toggleOpenItem(article.id)}
                />
            </li>)
            return (
                <div>
                    <h1>Article list</h1>
                    <ul>
                        {listItems}
                    </ul>
                </div>
            )
        }
    }
    
    export default oneOpen(ArticleList)

    ArticleListOld.js будет выглядеть так:

    import React, { Component }  from 'react'
    import Article from './Article'
    import oneOpen from './mixins/oneOpen'
    
    const ArticleList = React.createClass({
        mixins: [oneOpen],
        render() {
            const { articles } = this.props
    
            const listItems = articles.map((article) => <li key={article.id}>
                <Article article = {article}
                    isOpen = {this.isItemOpen(article.id)}
                    openArticle = {this.toggleOpenItem(article.id)}
                />
            </li>)
            return (
                <div>
                    <h1>Article list</h1>
                    <ul>
                        {listItems}
                    </ul>
                </div>
            )
        }
    })
    
    export default ArticleList

    Пожалуйста добавьте следующую запись в app.js, и удалите import  ArticleList’а:

    import ArticleList from './ArticleListOld

    Пожалуйста сравните наш код с тем что у Вас получился, и мы пойдем дальше. Все коммиты Вы сможете найти в репозитории.

    Read More:  Инструменты JavaScript / Node.js разработчика

    435258_8a75_3

    We are looking forward to meeting you on our website blog.soshace.com

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    bragin_pa

      Related Posts

      3. Уроки Express.js. Шаблонизация с EJS: Layout, Block, Partials

      December 16, 2016

      Уроки Express.js . Логгер, Конфигурация, Шаблонизация с EJS. Часть 2.

      December 2, 2016

      2. Уроки Express.js . Логгер, Конфигурация, Шаблонизация с EJS. Часть 1.

      November 24, 2016

      Comments are closed.

      Stay In Touch
      • Facebook
      • Twitter
      • Pinterest
      • Instagram
      • YouTube
      • Vimeo
      Don't Miss
      Events August 8, 2019

      HR Tech Conferences Worth Your Time [2019]

      This time around, we’ll cover the biggest HR Technology events that are due this year, starting from August and finishing up in November. Feel free to choose any of those, because they are guaranteed to be perfect opportunities to network and meet like-minded individuals who work in IT, web development, and tech recruitment.

      Strategic Approaches to Securing Startup Funding Successfully

      December 10, 2024

      Mastering Lean Project Management: Essential Principles Guide

      December 4, 2024

      Diam Maecenas Ultricies Mieget Wauris Bibendum Neque

      January 28, 2020

      Categories

      • AI & Automation
      • Angular
      • ASP.NET
      • AWS
      • B2B Leads
      • Beginners
      • Blogs
      • Business Growth
      • Case Studies
      • Comics
      • Consultation
      • Content & Leadership
      • CSS
      • Development
      • Django
      • E-commerce & Retail
      • Entrepreneurs
      • Entrepreneurship
      • Events
      • Express.js
      • Facebook Ads
      • Finance & Fintech
      • Flask
      • Flutter
      • Franchising
      • Funnel Strategy
      • Git
      • GraphQL
      • Home Services Marketing
      • Influencer & Community
      • Interview
      • Java
      • Java Spring
      • JavaScript
      • Job
      • Laravel
      • Lead Generation
      • Legal & Compliance
      • LinkedIn
      • Machine Learning
      • Marketing Trends
      • Medical Marketing
      • MSP Lead Generation
      • MSP Marketing
      • NestJS
      • Next.js
      • Node.js
      • Node.js Lessons
      • Paid Advertising
      • PHP
      • Podcasts
      • POS Tutorial
      • Programming
      • Programming
      • Python
      • React
      • React Lessons
      • React Native
      • React Native Lessons
      • Recruitment
      • Remote Job
      • SaaS & Tech
      • SEO & Analytics
      • Soshace
      • Startups
      • Swarm Intelligence
      • Tips
      • Trends
      • Vue
      • Wiki
      • WordPress
      Top Posts

      Effective Networking Strategies to Generate B2B Leads

      B2B Leads December 18, 2024

      Mastering Project Performance Reviews: A Step-by-Step Guide

      JavaScript December 9, 2024

      Advanced Mapmaking: Using d3, d3-scale and d3-zoom With Changing Data to Create Sophisticated Maps

      JavaScript March 11, 2020

      Effective Networking Strategies to Boost B2B Lead Generation

      B2B Leads November 26, 2024

      Subscribe to Updates

      Get The Latest News, Updates, And Amazing Offers

      About Us
      About Us

      Soshace Digital delivers comprehensive web design and development solutions tailored to your business objectives. Your website will be meticulously designed and developed by our team of seasoned professionals, who combine creative expertise with technical excellence to transform your vision into a high-impact, user-centric digital experience that elevates your brand and drives measurable results.

      7901 4th St N, Suite 28690
      Saint Petersburg, FL 33702-4305
      Phone: 1(877)SOSHACE

      Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
      Our Picks
      Wiki

      Заметка про распорядок дня

      Flask

      Implementing Machine Learning in Web Applications with Python and TensorFlow

      Interview

      Top 18 Interview Questions for Python Developers

      Most Popular

      Effective Strategies for Managing Scope Creep in Projects

      JavaScript

      The Critical Role of Code Reviews in Software Development

      Programming

      15. Уроки Node.js. Асинхронная разработка. Введение.

      Programming
      © 2025 Soshace Digital.
      • Home
      • About
      • Services
      • Contact Us
      • Privacy Policy
      • Terms & Conditions

      Type above and press Enter to search. Press Esc to cancel.