React具名插槽和作用域插槽
-
// 插槽的使用,首先插槽是在 组件标签内部组合的 JSX 内容,进行传递
-
// 因为 JSX 本身就是一个 类 js 对象, 插槽 直接使用 props.children 拿到了 JSX 直接渲染到页面
-
// 在 React 中,可以使用一个数组或者对象,通过索引或者属性实现具名插槽
-
// 函数式组件
-
const Header = (props: {
-
name: string;
-
children: {
-
blue: React.ReactNode;
-
yellow: React.ReactNode;
-
green: React.ReactNode;
-
pink: React.ReactNode;
-
};
-
}) => {
-
console.log(props.children)
-
/*
-
{
-
blue: <h2 style={{ color: 'blue' }}>header的插槽</h2>,
-
yellow: <h2 style={{ color: 'yellow' }}>header的插槽</h2>,
-
green: <h2 style={{ color: 'green' }}>header的插槽</h2>,
-
pink: <h2 style={{ color: 'pink' }}>header的插槽</h2>
-
}
-
*/
-
return (
-
<div>
-
<h2>{props.name}Header的h2</h2>
-
{props.children.blue}
-
</div>
-
)
-
}
-
// 类组件
-
class Content extends React.Component<any, any> {
-
render (): React.ReactNode {
-
console.log(this.props.children)
-
{/*[<h2 style={{ color: 'red' }}>content的插槽</h2>,
-
<h2 style={{ color: 'green' }}>content的插槽</h2>] */}
-
return (
-
<div>
-
<h2>React {this.props.version} 版本开始就提供了 Hooks 编程!</h2>
-
{this.props.children}
-
{this.props.children[0]}
-
</div>
-
)
-
}
-
}
-
const Footer = (props: { children: Function }) => {
-
return (
-
<>
-
<footer>Footer的footer</footer>
-
{
-
props.children("作用域插槽数据")
-
}
-
</>
-
)
-
}
-
class App extends React.Component<any, any>{
-
render (): React.ReactNode {
-
return (
-
// JSX 语法必须要有一个 父元素,如果不需要标签占位,可以直接使用 <> 即可
-
<>
-
<Header name="Header的name ">
-
{/* 具名插槽 */}
-
{
-
{
-
blue: <h2 style={{ color: 'blue' }}>header的插槽</h2>,
-
yellow: <h2 style={{ color: 'yellow' }}>header的插槽</h2>,
-
green: <h2 style={{ color: 'green' }}>header的插槽</h2>,
-
pink: <h2 style={{ color: 'pink' }}>header的插槽</h2>
-
}
-
}
-
</Header>
-
<Content version={16.8}>
-
{/* 具名插槽,数组实现 */}
-
{/* 如果插槽的数量为0,那么组件执行时获得的props.children是
-
undefined,如果插槽的数量为1,则是该值,如果大于1,则是一个数组 */}
-
<h2 style={{ color: 'red' }}>content的插槽</h2>
-
<h2 style={{ color: 'green' }}>content的插槽</h2>
-
</Content>
-
<Footer>
-
{/* 也可以是函数,
-
因为在某些场景下插槽的内容可能想要同时使用父组件域内和子组件域内的数据。
-
作用域插槽 */}
-
{
-
(v: string) => (<h2 style={{ color: 'green' }}>Footer的作用域插槽, {v}</h2>)
-
}
-
</Footer>
-
</>
-
)
-
}
-
}
运行结果:
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /boutique/detail/tanhgagkke
系列文章
更多
同类精品
更多
-
photoshop保存的图片太大微信发不了怎么办
PHP中文网 06-15 -
Android 11 保存文件到外部存储,并分享文件
Luke 10-12 -
word里面弄一个表格后上面的标题会跑到下面怎么办
PHP中文网 06-20 -
《学习通》视频自动暂停处理方法
HelloWorld317 07-05 -
photoshop扩展功能面板显示灰色怎么办
PHP中文网 06-14 -
微信公众号没有声音提示怎么办
PHP中文网 03-31 -
excel下划线不显示怎么办
PHP中文网 06-23 -
excel打印预览压线压字怎么办
PHP中文网 06-22 -
怎样阻止微信小程序自动打开
PHP中文网 06-13 -
TikTok加速器哪个好免费的TK加速器推荐
TK小达人 10-01