美文网首页
React导航栏封装

React导航栏封装

作者: kevin5979 | 来源:发表于2020-09-25 21:31 被阅读0次

    父子组件传值练习

    效果图


    image.png
    import React, {Component} from "react";
    import PropTypes from "prop-types"
    
    // 子组件
    class TabBarItem extends Component {
    
      render() {
        const {tab_bars, curr_index} = this.props
        return (
          <ul>
            {
              tab_bars.map((item, index) => {
                return (
                  <li
                    key={index}
                    onClick={e => this.props.fItemClick(index)}
                    className={curr_index === index ? "active" : null}
                  >
                    {item}</li>
                )
              })
            }
          </ul>
        )
      }
    }
    
    // props验证
    TabBarItem.propTypes = {
      tab_bars: PropTypes.array,
      curr_index: PropTypes.number,
      fItemClick: PropTypes.func
    }
    
    // 父组件
    export default class TabBar extends Component {
      constructor(props) {
        super(props);
        this.tab_bars = ["热销", "新上", "推荐"]
        this.state = {
          curr_index: 0,
          curr_title: "热销"
        }
      }
    
      fItemClick = (index) => {
        this.setState({
          curr_index: index,
          curr_title: this.tab_bars[index]
        })
      }
    
      render() {
        return (
          <div>
            {
              <TabBarItem
                tab_bars={this.tab_bars}
                curr_index={this.state.curr_index}
                fItemClick={index => this.fItemClick(index)}
              />
            }
            <p>{this.state.curr_title}</p>
          </div>
        )
      }
    }
    
    
    END

    相关文章

      网友评论

          本文标题:React导航栏封装

          本文链接:https://www.haomeiwen.com/subject/qsiuhktx.html