案例说明
用React
实现了一个tab切换组件,点击tab切换内容,点击内容切换tab。
我们先来看以下代码:
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})
}
render(){
const { titles,tabIndex } = this.state;
return (
<div className="app">
<TabControl titles={titles} tabClick={i=>this.tabClick(i)}></TabControl>
<h1>{titles[tabIndex]}</h1>
</div>
)
}
}
export default App
上面代码中,我们定义了一个App
组件,它内部使用了自定义的TabControl
组件。TabControl
组件是用来显示tab的,它接收一个titles
数组和一个回调函数tabClick
。tabClick
函数用来接收点击的tab的索引,然后通过setState
更新App
组件的tabIndex
状态。App
组件通过tabIndex
状态来决定显示哪个tab的内容。这里我们将titles
数组传入到子组件,将父类的方法tabClick
传入到子组件。
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 } = 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>
</div>
)
})
}
</div>
)
}
}
export default TabControl
TabControl组件接收两个属性,一个是titles
数组,一个是tabClick
回调函数。tabClick
函数用来接收点击的tab的索引,然后通过setState
更新TabControl
组件的currentIndex
状态。TabControl
组件通过currentIndex
状态来决定显示哪个tab的内容。这里我们将titles
数组传入到子组件,将父类的方法tabClick
传入到子组件。
这里我们注意几点:
1.我们可以在React
中使用{}
来包含一个执行单元块,例如{titles.map((item,index)=>{})}
。
2.我们可以在React
标签属性中使用{}
来包含一个表达式,例如<div className={index === currentIndex?'active':''}>
。
总结
通过以上案例,我们可以总结一下React中子组件向父组件发送数据的方法:
通过上面的案例,我们发现,组件通信的实现方式有很多种,例如:父组件向子组件发送数据,子组件向父组件发送数据,子组件向子组件发送数据,父组件向父组件发送数据等。在实际开发中,我们需要根据实际情况选择合适的通信方式。最后我们再附上完成后的效果图:
感谢大家观看,我们下次见
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我