七、【React拓展】类插槽 render-props

文章目录

  • 1、类插槽?
  • 2、实现
  • 3、实操
    • 3.1、CODE
    • 3.2、Result

1、类插槽?

学过 Vue 的小伙伴都知道 Vue 有一个 slot 插槽技术,点击访问 Vue 插槽 slot
React 本身没有直接提供这样的操作,那么我们如何实现类似 Vue 插槽 呢?

2、实现

}>
A组件:{this.props.render(内部state数据)}
C组件:读取A组件传入的数据显示 {this.props.data}

3、实操

3.1、CODE

代码修改自 五、【React拓展】Context 的Demo

import React, { Component } from 'react'

export default class A extends Component {

    state = {
        name: '张三'
    }

    render() {
        const { name } = this.state
        return (
            <div style={{
                background: 'orange',
                padding: 10
            }}>
                <h2>这是A组件</h2>
                <h4>A组件用户名是:{name}</h4>
                {/* 这个render只是普通属性名,可以任意取名,但是约定俗称写render */}
                <B render={data => <C data={data} />} name={name}/>
            </div>
        )
    }
}

class B extends Component {
    render() {
        const { name } = this.props
        return (
            <div style={{
                background: 'skyblue',
                padding: 10
            }}>
                <h2>这是B组件</h2>
                {
                	// 这就是类插槽!!!
                    this.props.render(name)
                }
            </div>
        )
    }
}

function C() {
    return (
        <div style={{
            background: 'gray',
            padding: 10
        }}>
            <h2>这是C组件</h2>
            <h4>接到外壳传来的数据是:{this.props.data.toString()}</h4>
        </div>
    )
}

3.2、Result

七、【React拓展】类插槽 render-props_第1张图片

你可能感兴趣的:(React,react.js,javascript,前端)