本文介绍了React组件内事件传参实现tab切换的示例代码,分享给大家,具体如下:
下面是一个向组件内函数传递参数的小例子
需求: 在页面的底部, 有四个按钮, 负责切换内容, 当按钮被点击时, 变为激活状态, 其余按钮恢复到未激活状态
分析: 我们首先要创建点击事件的处理函数, 当按钮被点击时, 将按钮的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"));
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
网页名称:React组件内事件传参实现tab切换的示例代码-创新互联
文章网址:https://www.cdcxhl.com/article10/dojcdo.html
成都网站建设公司_创新互联,为您提供全网营销推广、微信小程序、网站设计公司、网站内链、软件开发、网站制作
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联