作用域插槽
作用域插槽的使用场景: 当组件的内容是动态的,但是组件的样式是固定的,这时候可以使用作用域插槽,将动态的内容传递给组件,组件内部使用插槽渲染
我们先看一个例子:
import React,{Component} from "react";
import TabControl from './TabControl'
export class App extends Component{
constructor(){
super()
this.state = {
titles:["流行","新款","精选"],
tabIndex:0
}
}
tabClick(tabIndex){
this.setState({tabIndex})
}
getTabItem(item){
if(item === "流行"){
return <span>{item}</span>
}else if(item === "新款"){
return <button>{item}</button>
}else{
return <i>{item}</i>
}
}
render(){
const {titles,tabIndex} = this.state
return (
<div className="app">
<TabControl titles={titles}
tabClick={i => this.tabClick(i)}
// itemType={item=><button>{item}</button>}
itemType={item=>this.getTabItem(item)}>
</TabControl>
<h1>{titles[tabIndex]}</h1>
</div>
)
}
}
export default App;
上面代码中,我们使用了TabControl
组件,TabControl
组件内部通过itemType
属性来接收一个函数,这个函数用来渲染TabControl
组件内部的子组件,itemType
属性的值是一个函数,这个函数接收一个参数,这个参数就是TabControl
组件内部的子组件,然后通过itemType
属性的值来渲染TabControl
组件内部的子组件。
TabControl组件
我们先来看一下TabControl
组件的实现:
import React,{Component} from "react";
import "./style.css"
export class TabControl extends Component {
constructor(){
super()
this.state = {
currentIndex:0
}
}
itemClick(index){
// 1.自己保存最新的index
this.setState({currentIndex:index})
// 2.让父组件执行对应的函数
this.props.tabClick(index)
}
render(){
const { titles,itemType } = this.props
const { currentIndex } = this.state
return (
<div className="tab-control">
{
titles.map((item,index)=>{
return (
<div
className={`item ${index === currentIndex?"active":''}`}
key={item} onClick={e => this.itemClick(index)}>
{/* <span className='text'>{item}</span> */}
{itemType(item)}
</div>
)
})
}
</div>
)
}
}
export default TabControl;
以上代码中,TabControl
组件内部通过itemType
属性来接收一个函数,这个函数用来渲染TabControl
组件内部的子组件,itemType
属性的值是一个函数,这个函数接收一个参数,这个参数就是TabControl
组件内部的子组件,然后通过itemType
属性的值来渲染TabControl
组件内部的子组件。
这里我们需要注意看itemClick
方法,这个方法用来处理TabControl
组件内部的子组件的点击事件,这个方法内部首先保存最新的index
,然后让父组件执行对应的函数。
结尾
作用域插槽的使用场景: 当组件的内容是动态的,但是组件的样式是固定的,这时候可以使用作用域插槽,将动态的内容传递给组件,组件内部使用插槽渲染,这样就可以实现组件的复用。接着我们附上效果图:
感谢大家观看,我们下次见
of course like your web site but you need to test the spelling on quite a few of your posts. A number of them are rife with spelling problems and I in finding it very troublesome to inform the reality nevertheless I will surely come again again.
新年快乐!
十天看一部剧,还可以吧
@梦不见的梦 行,谢谢提醒,我优化一下
网站的速度有待提升,每次打开都要转半天还进不来呢
@React实战爱彼迎项目(二) - 程序员鸡皮 哪里有问题了,报错了吗?
@Teacher Du 那是怕你们毕不了业,我大学那会儿给小礼品
我们大学那会,献血还给学分~
@ab 我想去学网安,比如网警,但分也贼高😕
@夜 加油,你一样也可以成为程序员的,需要学习资料可以V我