前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >React组件内事件传参 实现tab切换

React组件内事件传参 实现tab切换

作者头像
zhaoolee
发布2018-07-05 10:40:17
1.2K0
发布2018-07-05 10:40:17
举报
文章被收录于专栏:木子昭的博客木子昭的博客
  • 组件内默认onClick事件触发函数actionClick, 是不带参数的,
  • 不带参数的写法: 如onClick= { actionItem }
  • 带参数的写法, onClick = { this.activateButton.bind(this, 0) }

下面是一个向组件内函数传递参数的小例子

  • 需求: 在页面的底部, 有四个按钮, 负责切换内容, 当按钮被点击时, 变为激活状态, 其余按钮恢复到未激活状态
  • 分析: 我们首先要创建点击事件的处理函数, 当按钮被点击时, 将按钮的id作为参数发送给处理函数, 处理函数激活对应当前id的按钮, 并将其余三个按钮调整到未激活状态
  • 实现: 用组件state创建一个含有四个元素的一维数组, 四个元素默认为零, 但界面中某个按钮被点击时, 组件内处理函数将一维数组内对应元素变为1, 其它元素变为0

效果演示:

  • 核心代码:
代码语言:javascript
复制
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层当前的状态, 方便业务的扩展

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.07.04 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 效果演示:
  • 小结
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档