案例说明
用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 TabControlTabControl组件接收两个属性,一个是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中子组件向父组件发送数据的方法:
通过上面的案例,我们发现,组件通信的实现方式有很多种,例如:父组件向子组件发送数据,子组件向父组件发送数据,子组件向子组件发送数据,父组件向父组件发送数据等。在实际开发中,我们需要根据实际情况选择合适的通信方式。最后我们再附上完成后的效果图:
感谢大家观看,我们下次见
我热爱 旅游专栏。令人惊艳了解路线。
欣赏你的照片, 我明白, 世界很美。感谢 旅行灵感。
读起来像小说。继续保持 带来的灵感。
让人精神焕发的 帖子! 我准备订票了。
以后焦虑了或者迷茫了记得回来看看
我非常喜欢 出行博客。鼓舞人心查看路线。
你们的博客 百分百 帮助选择路线。坚持!
信息丰富的 出行资源! 越来越棒!
My brother suggested I might like this blog. He was entirely right. This post actually made my day. You cann't imagine just how much time I had spent for this information! Thanks!
我热爱, 写得很实在。你的博客 就是 最好的例子。很出色。