• react组件通信 父组件与子组件互相通信


    • 父组件将自己的状态传递给子组件,子组件当做属性来接收,当父组件更改自己状态的时候,子组件接收到的属性就会发生改变
    • 父组件利用ref对子组件做标记,通过调用子组件的方法以更改子组件的状态,也可以调用子组件的方法

    父组件将自己的某个方法传递给子组件,在方法里可以做任意操作,比如可以更改状态,子组件通过this.props接收到父组件的方法后调用。

    在父组中定义ref引用

    import React, { Component, createRef } from 'react'
    import Child1 from './components/Child1'
    
    import Sub from './components/Sub'
    
    // 只有在类组件中才有生命周期
    export default class App extends Component {
    
      constructor(props) {
        super(props);
        // 定义一个成员属性用于ref引用的变量
        this.child = createRef()
      }
    
    
      state = {
        username: 'admin',
        sex: '男',
        count: 1
      }
    
      render() {
        return (
          <div>
             <Child1 ref={this.child} setCount={this.setCount.bind(this)} />
            <hr />
            <button onClick={this.fn.bind(this)}>修改一下子组件中的内容</button>
            <hr />
            <h3>{this.state.count}</h3> 
    
            <Sub />
    
    
          </div>
        )
      }
    
      fn() {
        // 通过ref得到子组件的实例对象
        const child = this.child.current
        // 调用子组件中的方法
        child.setTitle()
    
        // console.log(child.state.title);
      }
      setCount() {
        this.setState(prevState => {
          return { count: ++prevState.count };
        });
      }
    }

    子组件定义好数据源和修改数据源方法

    import React, { Component } from 'react'
    
    export default class Child1 extends Component {
      state = {
        title: '我是一个子组件'
      }
    
      componentDidMount(){
        setTimeout(() => {
          this.props.setCount()
        }, 3000);
      }
    
      render() {
        return (
          <div>
            {this.state.title}
          </div>
        )
      }
    
      setTitle() {
        this.setState({
          title: 'aaabbccc'
        })
      }
    
    }
    右侧打赏一下 代码改变世界一块二块也是爱
  • 相关阅读:
    从PubMed的HTML页面提取标题和摘要文本
    PDB(Protein Data Bank)数据格式详解
    Python+webdriver单选框/复选框定位
    Python+webdriver下拉菜单及鼠标悬浮菜单定位
    Python+webdriver切换iframe/frame
    Python+webdriver自动化脚本弹出框定位
    Python+webdriver脚本之多窗口切换新解
    python杂记
    Python+webdriver定位元素的几种方法
    Python函数
  • 原文地址:https://www.cnblogs.com/ht955/p/14690567.html
Copyright © 2020-2023  润新知