javascript 中 - 反应“子组件” - 文章子组件已满

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 中 - 反应“子组件” - 文章子组件已满相关的知识,希望对你有一定的参考价值。

// @flow
import React, { Component } from 'react';
import type { Node } from 'react';
import findByType from './findByType';
import css from './styles.css';

const Title = () => null;
const Subtitle = () => null;
const Metadata = () => null;
const Content = () => null;
const Comments = () => null;

type Props = {
  children?: Node,
  className?: string,
};

class Article extends Component<Props> {
  static Title: Function;
  static Subtitle: Function;
  static Metadata: Function;
  static Content: Function;
  static Comments: Function;
  
  renderTitle() {
    const { children } = this.props;
    const title = findByType(children, Title);
    if (!title) {
      return null;
    }
    return <div className={css.title}>{title.props.children}</div>;
  }

  renderSubtitle() {
    const { children } = this.props;
    const subtitle = findByType(children, Subtitle);
    if (!subtitle) {
      return null;
    }
    return (
      <div className={css.subtitle}>
        <div className={css.subtitleBox}>{subtitle}</div>
      </div>
    );
  }

  renderMetadata() {
    const { children } = this.props;
    const metadata = findByType(children, Metadata);

    if (!metadata) {
      return null;
    }

    return (
      <ul className={css.articlemetadata}>
        {metadata.props.children.map(child => {
          return <li className={css.item}>{child}</li>;
        })}
      </ul>
    );
  }

  renderContentAndComment() {
    const { children } = this.props;
    const content = findByType(children, Content);
    const comments = findByType(children, Comment);

    if (!content) {
      return null;
    }

    return (
      <div className={css.contentArticle}>
        <div className={css.contentTextStyle}>{content.props.children}</div>
        <span className={css.inlineComments}>
          {comments && comments.props.children}
        </span>
      </div>
    );
  }

  render() {
    const { children, className, ...rest } = this.props;

    return (
      <div className={css.mainContainer}>
        <div className={css.wrapper}>
          <div className={css.titleContainer}>
            {this.renderTitle()}
            {this.renderSubtitle()}
          </div>
          {this.renderMetadata()}
          {this.renderContentAndComment()}
        </div>
      </div>
    );
  }
}

Article.Title = Title;
Article.Subtitle = Subtitle;
Article.Metadata = Metadata;
Article.Content = Content;
Article.Comments = Comments;

export default Article;

以上是关于javascript 中 - 反应“子组件” - 文章子组件已满的主要内容,如果未能解决你的问题,请参考以下文章

在反应中添加子组件

反应无状态子组件不会更新父组件中的状态更改

如何在插槽中访问子组件的反应数据?

通过子组件在父组件中反应切换视图功能

在反应中从父dom节点中删除子组件

反应多个子组件的条件渲染