【JAVASCRIPT】React学习-巧用 props 的 children 属性实现内容填充

背景

平常写组件,经常遇到需要获取内容放入组件内部的情形。

实现方法

我们有两种实现方式

1. 自定义 props

render 的时候通过获取 this.props.content 填充到组件内部

const content = (<ul><li><span>分析1<span></li><li><span>分析1<span></li></ul>);
<Panel content={content} />

render () {
    return (<div>
        {this.props.content}
    </div>);
}

2. 利用 props 的 children

一般 props 是与用户定义的组件一一对应,但有一个例外 children ,表示组件内部的所有子节点。我们可以利用这个 props 属性,省略自定义content属性,直接获取this.props.children填充入组件。

这种方法的好处在于层级关系明显,因为内部节点有时候会很复杂,如果用自定义props属性,没法很快看清楚节点之间的包含关系。
注意点:
this.props.children 的值有三种可能,处理 this.props.children 的时候要注意判定:

  • 1) 如果当前组件没有子节点,是 undefined ;
  • 2)如果有一个子节点,数据类型是 object ;
  • 3)如果有多个子节点,数据类型就是 array 。
<Panel>
       <ul>
              <li><span>分析1<span></li>
              <li><span>分析1<span></li>
       </ul>
</Panel>


render () {
    return (<div>
        {this.props.children}
    </div>);
}

升级版,采用React.Children.map避免掉入this.props.children的坑

<Panel>
        <span>分析1<span>
        <span>分析1<span>
</Panel>

render() {

    return (<div>
        <ul>
        {
            React.children.map(this.props.children, (child)=>{
                return (<li>{child}</li>);
            });
        }
        </ul>
    </div>);
}

React.children 的方法

官方文档: https://facebook.github.io/react/docs/react-api.html#react.children.map

  • React.Children.map(children, function[(thisArg)]) 返回处理后的节点array
  • React.Children.forEach(chidlren, function[(thisArg)]) 不返回处理后的节点array,仅遍历节点,多用于处理数据!!!!
  • React.chidlren.count(children) 返回children个数
  • React.Children.only(children) 仅接受单个节点,超过一个报错
  • React.Chidlren.toArray(children) 把dom节点数组话,多用于render时slice节点

转载于:https://www.cnblogs.com/huxiaoyun90/p/6549217.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值