【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