zoukankan      html  css  js  c++  java
  • React----react组件传值

    react组件传值方式:
    (1)父传子:子组件标签定义自定义属性+子组件内部this.props接收
    传递:子组件在父组件中当做标签使用时,子组件标签定义自定义属性val,值为需要传递的值<One val={fatherMsg}></One>
    接收:子组件内部通过this.props.val进行接收(使用解构赋值能简化代码,将val先解构出来,直接使用)
    render(){
        let {val} = this.props
        return (
            <div className="one"><p>one接收到app传递过来的值为:{val}</p></div>
        )
    }
    (2)子传父:子组件标签定义自定义属性fnName+子组件内部this.props.fnName来触发
    传递:子组件内部通过this.props.fnName来触发这个函数,参数通过函数进行传递
    render(){
        return (
            <div className="twoSon">
                <button onClick={this.handleClick.bind(this)}>发送给two</button>
            </div>
        )
    }
    handleClick(){this.props.fnName(this.state.sonMsg)}

    接收:子组件在父组件中当做标签使用时,子组件标签定义自定义属性fnName,值为一个函数;最后通过参数进行接收传递过来的数据

    render(){
        let {msg} = this.state;
        return (
            <div className="two">
                <p>{msg}</p>
                <TwoSon fnName={this.handleGet.bind(this)}></TwoSon>
            </div>
        )
    }
    handleGet(val){
        this.setState({msg:'接收到twoSon传递过来的值为:'+val})
    }
    (3)非父子:手动封装事件订阅$on、$emit;传值组件写事件函数,函数中$emit("fnName",val);接收值componentDidMount声明函数中通过$on("fnName",(val)=>{})来接收val
    例如:传值组件:调用 $emit:
    render(){
        return (
            <div className="thr"><button onClick={this.handleClick.bind(this)}>发送给fou</button></div>
        )
    }
    handleClick(){Observer.$emit("fnName",this.state.thrMsg)}

    接收组件:调用 $on:

    render(){
        return (
            <div className="fou"><p>接收到thr传递过来的值为:{this.state.msg}</p></div>
        )
    }
    componentDidMount(){
        Observer.$on("fnName",(val)=>{this.setState({msg:val})})
    }
  • 相关阅读:
    selenium屏蔽浏览器检测
    cookies字符串转化为字典
    python压缩图片大小
    python异步爬虫aiohttp
    python通过命令行接收参数
    hustoj实现远程判题的两种方案
    SqlLocalDB工具的一些有趣发现
    Chrome中编译安装vue-devtools插件
    用友政务表格技术应用开发实践:预算一体化产品核心功能搭建
    企业表格技术应用开发案例大赛圆满落幕!
  • 原文地址:https://www.cnblogs.com/snowstorm22/p/10559622.html
Copyright © 2011-2022 走看看