react 父子通信| 青训营笔记

80 阅读1分钟

这是我参与【第五届青训营】笔记创作活动的第5天

一、父传子

1.1.父组件传递数组给子组件

  • 父组件通过 属性=值的形式来传递给子组件数据
  • 子组件通过props参数获取父组件传递过来的数据

父组件

数据为

  • banner
  • productList

在使用子组件MainBanner、MainProduct中通过属性=值进行传递数据

  • 子组件MainBanner

  • 子组件MainProduct

1.2.对传递给子组件的数据进行验证

如果需要对传递子组件的数据进行验证,那么可以通过prop-types库进行参数验证

import PropTypes from 'prop-types';

Data.propTypes = {
  name:PropTypes.string,
  age:PropTypes.number
}

具体看官方文档:zh-hans.reactjs.org/docs/typech…

如果希望有默认值:使用defaultProps

二、子传父

  • 通过props,父组件给子组件穿第一个回调函数,在子组件中调用这个函数
  • 父组件

  • 子组件1

  • 子组件2

三、tabControl练习父子通信

  • 父组件
import { Component } from "react";
import TabControl from "./TabControl";

export class App extends Component {
    constructor() {
        super()

        this.state = {
            titles: ["流行", "新款", "精选"],
            tabIndex:0
        }
    }
    tabClick(tabIndex) {
        this.setState({tabIndex})
    }
    render() {
        const {titles, tabIndex} = this.state
        return (
            <div className="app">
                <TabControl titles={titles} tabClick={i => this.tabClick(i)}></TabControl>
                <h1>{titles[tabIndex]}</h1>
            </div>
        )
    }
}
export default App
  • 子组件
import React, { Component } from 'react'
import "./style.css"

export class TabControl extends Component {
  constructor() {
    super()

    this.state = {
      currentIndex: 0
    }
  }

  itemClick(index) {
    // 1.自己保存最新的index
    this.setState({ currentIndex: index })

    // 2.让父组件执行对应的函数
    this.props.tabClick(index)
  }

  render() {
    const { titles } = this.props
    const { currentIndex } = this.state

    return (
      <div className='tab-control'>
        {
          titles.map((item, index) => {
            return (
              <div 
                className={`item ${index === currentIndex?'active':''}`} 
                key={item}
                onClick={e => this.itemClick(index)}
              >
                <span className='text'>{item}</span>
              </div>
            )
          })
        }
      </div>
    )
  }
}

export default TabControl
  • 子组件样式
.tab-control {
    display: flex;
    align-items: center;
    height: 40px;
    text-align: center;
  }
  
  .tab-control .item {
    flex: 1;
  }
  
  .tab-control .item.active {
    color: rgb(240, 144, 1);
  }
  
  .tab-control .item.active .text {
    padding: 3px;
    border-bottom: 3px solid rgb(245, 162, 9);
  }