美文网首页
React 父组件 子组件之间的传值

React 父组件 子组件之间的传值

作者: 砚婉儿 | 来源:发表于2020-11-13 10:01 被阅读0次

    1、父组件向子组件传值:

    父组件 App.js:

    import React,{ Component } from "react";
    import Sub from "./SubComponent.js";
    import "./App.css";
    
    export default class App extends Component{
    
        render(){
            return(
                <div>
                    <Sub title = "今年过节不收礼" />
                </div>
            )
        }
    }
    

    子组件 SubComponent.js:

    import React from "react";
    
    const Sub = (props) => {
        return(
            <h1>
                { props.title }
            </h1>
        )
    }
    
    export default Sub;
    

    2、子组件向父组件传值:

    子组件 SubComponent.js:

    import React from "react";
    
    const Sub = (props) => {
        const cb = (msg) => {
            return () => {
                props.callback(msg)
            }
        }
        return(
            <div>
                <button onClick = { cb("我们通信把") }>点击我</button>
            </div>
        )
    }
    
    export default Sub;
    

    父组件 App.js:

    import React,{ Component } from "react";
    import Sub from "./SubComponent.js";
    import "./App.css";
    
    export default class App extends Component{
        callback(msg){
            console.log(msg);
        }
        render(){
            return(
                <div>
                    <Sub callback = { this.callback.bind(this) } />
                </div>
            )
        }
    }
    

    相关文章

      网友评论

          本文标题:React 父组件 子组件之间的传值

          本文链接:https://www.haomeiwen.com/subject/ukkvbktx.html