组件通信案例

组件通信案例

 

 

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
}
 
 

组件通信案例

上一篇:docker 使用rabbitmq 及在Django项目中的配置


下一篇:pip 环境搭建