react组合

react 学习笔记–组合
有些组件无法提前知晓它们子组件的具体内容。
可以使用一个特殊的 children prop 来将他们的子组件传递到渲染结果中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function ParentComponent(props) {
return (
<div className={'ParentComponent ParentComponent-' + props.color}>
{props.children}
</div>
);
}

function renderComponent() {
return (
<ParentComponent color="blue">
<h1 className="title">
111
</h1>
<p className="message">
222
</p>
</ParentComponent>
);
}

还可以预留几个下几个位置,这种情况下我们可以不实用children

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function ParentComponent(props) {
return (
<div className="ParentComponent">
<div className="ParentComponent-left">
{props.left}
</div>
<div className="ParentComponent-right">
{props.right}
</div>
</div>
);
}

function App() {
return (
<ParentComponent
left={
<Component1 />
}
right={
<Component2 />
} />
);
}
PenZ wechat
交个朋友吧
点滴分享,您的支持将极大的鼓励我!