由于在React组件中写的内容会被挂载到props中,以此来实现类似vue中的插槽功能

这是最外层代码

import React, { Component } from 'react'
import NavBar from './NavBar'
import NavBar2 from './NavBar2'

export default class App extends Component {
  render() {
    return (
      <div>
        <NavBar>
          <span>aaa</span>
          <strong>bbb</strong>
          <a href="/#">ccc</a>
        </NavBar>

        <NavBar2 leftslot={<span>aaa</span>}
        centerslot={<strong>bbb</strong>}
        rightslot={<a href="/#">ccc</a>}/>
      </div>
    )
  }
}

1.用this.props.children[index]

import React, { Component } from 'react'

import './style.css'
export default class NavBar extends Component {
  render () {
    return (
      <div className="nav-bar">
        <div className="nav-left">
          {this.props.children[0]}
        </div>
        <div className="nav-center">
          {this.props.children[1]}
        </div>
        <div className="nav-right">
          {this.props.children[2]}
        </div>
      </div>
    )
  }
}

2.用直接命名方式

import React, { Component } from 'react'

import './style.css'
export default class NavBar extends Component {
  render () {
    const {leftslot, centerslot,rightslot} = this.props
    return (
      <div className="nav-bar">
        <div className="nav-left">
          {leftslot}
        </div>
        <div className="nav-center">
          {centerslot}
        </div>
        <div className="nav-right">
          {rightslot}
        </div>
      </div>
    )
  }
}
Logo

前往低代码交流专区

更多推荐