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

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

  • map
  • forEach
  • count,
  • toArray
  • only

实际应用

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

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

最终实现效果:

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

模拟实现:

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
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;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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,使用方法如下:

1
2
3
4
5
6
7
8
9
10
React.cloneElement(
element,
[props],
[...children]
)

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