zoukankan      html  css  js  c++  java
  • 父子通讯之单向数据流

    react

    单向数据流:如父组件通过props将数据传递给子组件

    react父组件传值给子组件都是单向数据流,且子组件中无法直接修改传入的属性值

    原因:子组件传入的props,当父组件改变此值时,子组件的props也会改变,说明子组件的该属性是引用和指向父组件的传入变量,而不是简单的拷贝子组件在父组件内,则无权让父组件重新渲染DOM,但如果直接允许更改传入的props会让父组件重新渲染而子组件也会重新渲染,会导致逻辑错误;因此父组件到子组件是单向数据流模式

    更改传入的props的解决方式:

    react中是直接将携带有父组件上下文对象的操作属性的函数传入到子组件中,然后绑定到事件上

    示例代码:
    父组件:

    <Children userName={userName} updateUser={this.updateUser.bind(this)} />

    子组件:

    <p>{this.props.userName}</p>

    <button onClick={this.props.updateUser}>修改</button>

    注:子组件(如Children)将传入的props设置为自己的数据时,可以为Children添加ref='children',将父组件的某数据设置为this.refs.children.state.xxx即可

    (相当于是在子组件中通过父组件修改props

    vue

    vue中通过创建临时变量拷贝传入props,然后在事件中通过$emit(func,model)通知父组件刷新数据

    示例:

    子组件:

    <p v-text='userName'></p>

    <button @click='updateUser()'>修改</button>

    updateUser(){

          this.$emit('update:userNmae',tmp_userName);

    }

    父组件:

    <Children :userName.sync='userName'>

    双向绑定是元素绑定data,同时又能修改data

  • 相关阅读:
    Dynamically allocated memory 动态分配内存【malloc】Memory leaks 内存泄漏
    const pointers
    heap是堆,stack是栈
    Java中使用Cookie
    Postman注册、登录、导出、导入
    HttpServletRequest get post 入参
    判断设置的时间是否大于当前时间
    JS回车登录
    一个普通的Ajax
    Java工具类
  • 原文地址:https://www.cnblogs.com/ggymx/p/12154877.html
Copyright © 2011-2022 走看看