React插槽的实现


方法一:通过 children获取

class App extends React.Component {
  render() {
    return (
      
{/*
*/} //子组件 aaa bbb ccc 详情 更多 {/* */}
) } } export default App;

子组件

export default class NavBar extends Component {
    render() {
        return (
            
{this.props.children[0]} //通过获取父组件传过来的数据下标展示不一样的数据
{this.props.children[1]}
{this.props.children[2]}
) } }

方法二:通过变量来插入数据 (推荐)

父组件

class App extends React.Component {
  render() {
    return (
      
<NavBar2 leftSlot={aaa} //使用变量定义3个数据 centerSlot={bbb} rightSlot={ccc} />
) } }

子组件

export default class NavBar2 extends Component {
    render() {
        const {leftSlot,centerSlot,rightSlot} = this.props;
        return (
            
{leftSlot}
{centerSlot}
{rightSlot}
) } }