组件复合
复合组件给予你足够的灵活去定义组件的外观和行为,而且是以一种明确和安全的方式进行.如果组件间有公用的非UI逻辑,将它们抽取为JS模块导入使用而不是继承它/src/components/Composition.js
// Dialog作为容器不关心内容和逻辑
function Dialog(props){
return <div style={{ border: "4px solid blue" }}>{props.children}</div>
}
// WelcomeDialog通过复合提供内容
function WelcomDialog() {
return (
<Dialog>
<h1>欢迎光临</h1>
<p>感谢使用react</p>
</Dialog>
)
}
export default function (){
return <WelcomDialog></WelcomDialog>
}
栗子
import React
from 'react'
function Dialog(props
) {
return <div style
={{ border
: `4px solid ${props.color || 'blue'}` }}>
{props
.children
}
<div className
="footer">
{props
.footer
}
</div
>
</div
>
}
function WelcomeDialog(props
) {
return (
<Dialog
{...props
}>
<h1
>欢迎光临
</h1
>
<p
>感谢使用react
</p
>
</Dialog
>
)
}
export default function() {
const footer
= <button
>相当于
-- 具名插槽
</button
>
return <WelcomeDialog color
="red" footer
={footer
}></WelcomeDialog
>
}