react 插槽

插槽

子组件中的内容,会被放进this.props.children这个数组里

	1、在父组件标签中的子组件B添加内容
		<B>xx</B>
	2、设置插槽内容在子组件显示
		{this.props.children}

	3、子组件获取插槽内容中标签上的参数
		因为内容按数组放置
		{this.props.children[索引].props['data-xx']}

	4、可通过对this.props.children的循环,来进行内容、参数处理

	搭配this.props.children相关的方法
	
	 (1)遍历插槽内的子元素
		React.Children.map(this.props.children,(ele,index)=>{
			ele.props.键名获取插槽内容的标签属性
			return  xx
		})
		
		React.Children.forEach(children, function[(thisArg)])	和map遍历相似,不返回数组
		
	 (2)获取子元素数目
	 	React.Children.count(this.props.children)
	 
	 (3)验证children是否只有一个子节点(一个 React 元素),如果有则返回它,否则此方法会抛出错误。
	 	React.Children.only(this.props.children)
	 
	 (4)将children这个复杂的数据结构以数组的方式扁平展开并返回,并为每个子节点分配一个 key。
	 	当你想要在渲染函数中操作子节点的集合时,它会非常实用,特别是当你想要在向下传递this.props.children之前对内容重新排序或获取子集时
	 	React.Children.toArray(this.props.children)

代码示例:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import './1.css'
{/*https://c.m.163.com/ug/api/wuhan/app/index/feiyan-data-list?t=1582528861997
https://c.m.163.com/ug/api/wuhan/app/data/list-total?t=1582514346850*/}

class A extends React.Component{
	constructor(props)
	{
		super(props);
		console.log(props);
	}
	render()
	{
		return(
			<div>hh
				<As>
					<h1 data-po='top'>哈哈1</h1>
					<h1 data-po='main'>哈哈2</h1>
					<h1 data-po='footer'>哈哈3</h1>
				</As>
			</div>
		)
	}
}
//子组件
class As extends React.Component{
	constructor(props)
	{
		super(props);
		console.log(props);
	}
	render()
	{
	//循环获取各个子组件外加参数获取
		let one,two,thre;
		this.props.children.forEach(function(item,index){
			if(item.props['data-po']=='top')
			{
				one=item;
			}else if(item.props['data-po']=='main')
			{
				two=item;
			}else{
				thre=item;
			}
		})

		return(
			<div>
				A的子组件
				//获得插槽内容中第一个标签的传入参数
				{this.props.children[0].props['data-po']}
				//将获得的各个插槽内容,分别显示
				<div className='top'>
					one
				</div>
				<div className='main'>
					two
				</div>
				<div className='footer'>
					thre
				</div>


			</div>
		)
	}
}



ReactDOM.render(<A/>, document.getElementById('root'));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值