本文介绍了React组件内事件传参实现tab切换的示例代码,分享给大家,具体如下:
- 组件内默认onClick事件触发函数actionClick, 是不带参数的,
- 不带参数的写法: 如onClick= { actionItem }
- 带参数的写法, onClick = { this.activateButton.bind(this, 0) }
下面是一个向组件内函数传递参数的小例子
需求: 在页面的底部, 有四个按钮, 负责切换内容, 当按钮被点击时, 变为激活状态, 其余按钮恢复到未激活状态
分析: 我们首先要创建点击事件的处理函数, 当按钮被点击时, 将按钮的id作为参数发送给处理函数, 处理函数激活对应当前id的按钮, 并将其余三个按钮调整到未激活状态
实现: 用组件state创建一个含有四个元素的一维数组, 四个元素默认为零, 但界面中某个按钮被点击时, 组件内处理函数将一维数组内对应元素变为1, 其它元素变为0
效果演示:
核心代码:
import 'babel-polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; import './index.scss' class TabButton extends React.Component { constructor(props) { super(props); this.state = { markArray: [0, 0, 0, 0], itemClassName:'tab-button-item' }; this.activateButton = this.activateButton.bind(this); } // 根据参数id, 来确定激活四个item中的哪一个 activateButton(id) { let tmpMarkArray = [0, 0, 0, 0] tmpMarkArray[id] = 1; this.setState({markArray: tmpMarkArray}); } render() { return ( <div className = "tab-button" > <div className = {(this.state.markArray)[0] "tab-button-item-active" : "tab-button-item" } onClick = { this.activateButton.bind(this, 0) } > 零 </div> <div className = {(this.state.markArray)[1] "tab-button-item-active" : "tab-button-item" } onClick = { this.activateButton.bind(this, 1) } > 壹 </div> <div className = {(this.state.markArray)[2] "tab-button-item-active" : "tab-button-item" } onClick = { this.activateButton.bind(this, 2) } > 贰 </div> <div className = {(this.state.markArray)[3] "tab-button-item-active" : "tab-button-item" } onClick = { this.activateButton.bind(this, 3) } > 叁 </div> </div>) } } ReactDOM.render( < TabButton / > , document.getElementById("root"));
小结
上面的例子也可以通过event.target.value
快速实现,但这个demo的扩展性更好, 在版本迭代过程中, 我们可以传递数量更多的参数, 详尽的描述UI层当前的状态, 方便业务的扩展
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
风云阁资源网 Design By www.bgabc.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
风云阁资源网 Design By www.bgabc.com
暂无评论...
RTX 5090要首发 性能要翻倍!三星展示GDDR7显存
三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。
首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。
据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。
更新日志
2024年09月21日
2024年09月21日
- 群星.2024-凡人歌电视剧原声带【正午阳光】【FLAC分轨】
- 黑神话悟空上品骨悚然精魄获取方法一览|上品骨悚然精魄收集攻略
- 《演灭Evotinction》正式登陆多平台发售!带你进入科幻潜行新境界
- 命运圣契2024公测最新兑换码大全 命运圣契开服可用兑换码汇总
- 银霞.1979-《回答·兰花草》新加坡限量复黑版[WAV+CUE]
- 王菲.1996-《乐乐精逊SACD日本限量版[WAV+CUE]
- 王菲.1996-《乐乐精逊SACD日本限量版[WAV+CUE]
- 不止黑神话!杭州给原创企业真金白银扶持 打造“杭州游戏”品牌
- 很有多样性:《战锤》首次引入非二元性别角色
- 《少女前线2:追放》项目组将裁员 官方:进一步优化组织结构
- 陈慧琳.2002-闪亮每一天新歌+精选2CD【正东】【WAV+CUE】
- 袁培华.1992-有缘【歌林】【WAV+CUE】
- 王瑞霞.1996-是我太软心【名冠】【WAV+CUE】
- 《谭维维 30首经典流行歌曲精选辑 2CD》[WAV/分轨][1.1GB]
- 《赵传 出道三十年全新大碟 你过得还好吗》[WAV/分轨][460MB]