首页 > 其他 > 详细

组件通信案例

时间:2021-08-11 15:34:09      阅读:5      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

 

app.js

 

import React, { Component } from ‘react‘
import TabControll from ‘./tabControll‘
export default class App extends Component {
    constructor(props){
        super(props);

        this.titles = [‘新款‘,‘精选‘,‘热门‘];
        this.state = {
            currentTitle:‘新款‘, 
        }
    }
    render() {
        const {currentTitle,titles} = this.state;
        return (
            <div>
                <TabControll itemClick={index=>this.itemClick(index)} titles={this.titles}/>
                 <h2>{currentTitle}</h2>
            </div>
        )
    }

    itemClick(index){
        // console.log(index); 
        this.setState({
            currentTitle: this.titles[index]
        })
    }
}
-----
style.css
-------
   
.tab-controll{
    display: flex; 
    height: 44px;
    line-height: 44px;
}

.tab-item{
    flex: 1;
    text-align: center;
}
 
.tab-item.active{
    color: red;
}

.tab-item.active span{
    padding: 5px 8px;
    border-bottom: 3px solid red;
}
-------------
tabControll.js
--------------
   
import React, { Component } from ‘react‘
import PropTypes from ‘prop-types‘;
import ‘./style.css‘
export default class TabControll extends Component {
    constructor(props){
        super(props);
        this.state = {
            currentIndex:0
        }
    }

    render() {
        const {titles} = this.props; 
        const {currentIndex} = this.state; 
        return (
            <div className="tab-controll"> 
                {
                    titles.map((item,index) => {
                        return (
                            <div 
                                className = {"tab-item " + (currentIndex === index ? ‘ active‘ : ‘‘)} 
                                key={index}
                                onClick = {e => this.itemClick(index)} >
                                <span>{item}</span> 
                            </div>    
                        ) 
                    } )
                }  
            </div>
        )
    }

    itemClick(index){
        this.setState({
            currentIndex:index
        })

        const {itemClick} = this.props;
        itemClick(index);
    }

}

PropTypes.PropTypes = {
    titles:PropTypes.array.isRequired
}
 
 

组件通信案例

原文:https://www.cnblogs.com/eric-share/p/15127663.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!