React插槽
有趣的老凌 人气:0需求
我们自己写了个组件,引用组件时想要在组件中写入内容,并且写入的内容可以被组件识别、控制,用过Vue的同学肯定会立刻想到slot插槽,react也支持插槽功能,下面我们用react开发一个支持插槽功能的组件。
核心思想
父组件在子组件中传入的三个div,这三个div会默认通过props传到子组件中,然后我们在子组件中控制children的渲染即可。
核心代码
// 015 使用插槽 import React from 'react'; import ReactDOM from 'react-dom'; // 父组件 class ParentDom extends React.Component { constructor(props) { super(props) this.state = { heardData:"头部数据", footData:"底部数据", contentData:"内容数据" } } componentDidMount() { } render() { return ( <div> <h1>015使用插槽</h1> <ChildDom > <div data-position="heard" >这是头部</div> <div data-position="content" >这是内容 丨{this.state.contentData}</div> <div data-position="foot" >这是底部</div> </ChildDom> </div> ) } } // 子组件 class ChildDom extends React.Component { constructor(props) { super(props) } render() { let heard,content,foot; this.props.children.forEach(item =>{ if(item.props['data-position'] == 'heard'){ heard = item }else if(item.props['data-position'] == 'content'){ content = item }else if(item.props['data-position'] == 'foot'){ foot = item } }) return ( <div > <p>我是子组件</p> <div className="heard"> {heard} </div> <div className="content"> {content} </div> <div className="foot"> {foot} </div> </div> ) } } export default function () { ReactDOM.render( <ParentDom />, document.querySelector("#example15") ); }
展示效果
React实现插槽的两种方式
由于在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="/#" rel="external nofollow" rel="external nofollow" >ccc</a> </NavBar> <NavBar2 leftslot={<span>aaa</span>} centerslot={<strong>bbb</strong>} rightslot={<a href="/#" rel="external nofollow" rel="external nofollow" >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> ) } }
加载全部内容