React学习总结6--children

2019-08-15  本文已影响0人  琉璃_xin

demos源码
每个组件都可以获取到 props.children。它包含组件的开始标签和结束标签之间的内容。

react提供了一系列的方法来方便处理children。

实际应用

在实际项目中的应用,我们可以对默认的children进行增加处理来达到我们的目的。很多的UI组件就使用了这个属性。
antd的Button组件:

<Button type="primary">Primary</Button>

最终实现效果:

<button type="button" class="ant-btn ant-btn-primary"><span>Primary</span></button>

模拟实现:

import React, { Component } from "react";
import PropTypes from "prop-types";
import classNames from "classnames";

import("./index.css");

const rxTwoCNChar = /^[\u4e00-\u9fa5]{2}$/;
const isTwoCNChar = rxTwoCNChar.test.bind(rxTwoCNChar);
function isString(str) {
    return typeof str === "string";
}

function insertSpace(child, needInserted) {
    if (child == null) {
        return;
    }
    const SPACE = needInserted ? " " : "";
    if (
        typeof child !== "string" &&
        typeof child !== "number" &&
        isString(child.type) &&
        isTwoCNChar(child.props.children)
    ) {
        return React.cloneElement(
            child,
            {},
            child.props.children.split("").join(SPACE)
        );
    }

    if (typeof child === "string") {
        if (isTwoCNChar(child)) {
            child = child.split("").join(SPACE);
        }
        return <span>{child}</span>;
    }
    return child;
}

class Button extends Component {
    static defaultProps = {
        htmlType: "button",
        type: "default"
    };

    static propTypes = {
        type: PropTypes.string,
        className: PropTypes.string
    };

    handleClick = e => {
        const { onClick } = this.props;
        if (onClick) {
            onClick(e);
        }
    };

    render() {
        const { type, className, children, htmlType, ...rest } = this.props;
        const kids = insertSpace(children, true);
        const classes = classNames("ant", className, {
            [`ant-${type}`]: type
        });

        const buttonNode = (
            <button
                type={htmlType}
                className={classes}
                onClick={this.handleClick}
                {...rest}
            >
                {kids}
            </button>
        );

        return buttonNode;
    }
}

export default Button;
import React, { Component } from 'react';
import Button from './Button';

class ChildrenCom extends Component {
  render() {
    return (
      <div>
        <Button type="primary">添加</Button>
        <Button onClick={(e) => {alert(e)}}>删除</Button>
      </div>
    )
  }
}

export default ChildrenCom;

上边实现过程中使用了React.cloneElement,使用方法如下:

React.cloneElement(
  element,
  [props],
  [...children]
)

const {children,...otherPorps}=this.porps
React.Children.map(children,child=>{
    React.cloneElement(child,otherPorps)
})
上一篇下一篇

猜你喜欢

热点阅读