问题导向
组件复合Composition?
如果你都有了答案,可以忽略本文章,或去react学习地图寻找更多答案
组件复合
作用:组件拓展与复用,自定义组件的外观和行为
如何使用:使用组件包裹内容,传递props.children,chilren可以是任意的JS表达式
const App = (props) => {
传递button给组件
const footer = <button>具名插槽</button>
传递color属性
return <WelcomeDialog color='green' footer={footer} />
}
WelcomeDialog通过复合提供内容
function WelcomeDialog(props){
return(
重点:使用展开运算符,接收App传递的color属性和footer,传给dialog
<Dialog {...props}>
<h1>hello</h1>
<p>react</p>
</Dialog>
)
}
Dialog作为容器不关心内容和逻辑
function Dialog(props) {
return (
<div style={{border:`4px solid ${props.color || 'blue'}`}}>
{props.children} //children是WelcomeDialog的H1和p标签
<div>
{props.footer} //具名插槽,有名字的插槽,是button
</div>
</div>
)
}
学习更多