react_07组件化开发(二)

2021-07-20  本文已影响0人  小话001

补充:

思考
打印结果
分析:
源码贴图
react这么操作应该是为了避免用户忘记传props,所以现在可传可不传。

子调用父函数通信:

//app.js
import React, { Component } from "react";
export default class App extends Component {
  constructor() {
    super();
    this.state = {
      counter:10
    };
  }
  render() {
    return (
      <div>
        <h2>App组件</h2>
         <h3>{this.state.counter}</h3>
        <hr />
        {/* <Childtest name="方式一" age={18}  addNum={e=>this.add()}  /> */}
        {/* <Childtest name="方式二" age={18}  addNum={this.add.bind(this)}  /> */}
        <Childtest name="方式三" age={18}  addNum={this.increament}  />
        <hr />
      </div>
    );
  }
  add(){
    this.setState(
      {
        counter:this.state.counter+1,
      }
    )
  }
  increament=()=>{
    this.setState(
      {
        counter:this.state.counter+1,
      }
    )
  }
}
class Childtest extends Component {
  render() {
    const {addNum}=this.props;
    return (
      <div>
         <h2>子组件</h2>
         <button onClick={addNum}>+1</button>
      </div>
    );
  }
}

案例:

效果预览
//app.js
import React, { Component } from "react";
export default class App extends Component {
  constructor() {
    super();
    this.tabs=["流行", "新款", "精选"];//如果不变的东西一般放在这,不用全部放在state里面
    this.state = {
      counter: 10,
      tabIndex:0
    };
  }
  render() {
    return (
      <div>
        <Childtest tabs={this.tabs} Index={(ChildValue)=>this.getIndex(ChildValue)} />
        <div>
            <h3>内容根据tab切换变化:</h3>
            <p>{this.tabs[this.state.tabIndex]}</p>
        </div>
      </div>
    );
  }
  getIndex(value){
    this.setState({
      tabIndex:value
    })
  }
}

class Childtest extends Component {
  constructor(){
    super()
    this.state={
      currentIndex:0
    }
  }
  render() {
    const { tabs,Index } = this.props;
    return (
      <div>
        <div className="tabbar">
          {tabs.map((item,index) => {
            return (
              <div key={item} className="tab-item">
                <span 
                  className={ this.state.currentIndex===index?"active":""}
                  onClick={e=>this.tabClick(index,Index)}>
                  {item}
                </span>
              </div>
            );
          })}
        </div>
      </div>
    );
  }
  tabClick(index,fn){
    console.log(index);//0,1,2
    //同时把这个序号传给父组件,然后父组件根据index 显示对应的文字,fn在这解构也行,如果不传的话
    fn(index);
    this.setState({
      currentIndex:index
    })
  }
}
//style.css
body{
  margin: 0;
  padding: 0;
}
.tabbar{
  display: flex;
  height: 44px;
  line-height: 44px;
  justify-content: space-around;
}
.tab-item{
    flex: 1;
    text-align: center;
}
.tab-item span{
  padding: 5px 8px;
}
.tab-item span.active{
  border-bottom: 2px solid red;
  color: red;
}
上一篇 下一篇

猜你喜欢

热点阅读