父子組件傳值(子組件傳遞父組件)


父組件js

 

import React, { Component } from 'react';
import Son from './Son'
import './Father.css'

class Father extends Component {
    constructor(props) {
        super(props);
        this.state = {
            sonValue: null
        }
    }
    
    
    render() {

        let {sonValue} = this.state;

        return (
            <div className="father">
                <h1>我是父組件</h1>
                <p>接收到的數據為:{sonValue}</p>

                <Son onSend={this.handleAction}/>

            </div>
        );
    }

    handleAction = (data)=>{
        console.log('handleAction執行了');
        this.setState({sonValue: data});
    }

}

export default Father;

 

子組件js

 

import React, { Component } from 'react';
import './Son.css'

class Son extends Component {

    constructor(props) {
        super(props);
        this.state = {
            inputVal: ''
        }
    }
    

    render() {

        // console.log(this.props.onSend);
        // this.props.onSend(1,2,3,4);

        let {inputVal} = this.state;

        return (
            <div className="son">
                <h1>我是子組件</h1>

                <input type="text" value={inputVal} onChange={this.changeAction}/>
                <button onClick={()=>{
                    //調用父組件的函數,傳入參數,實現子組件向父組件的傳值
                    this.props.onSend(inputVal);
                }}>發送</button>

            </div>
        );
    }

    changeAction = (ev)=>{
        this.setState({inputVal: ev.target.value});
    }
}

export default Son;

 

父組件css

 

.father{
    padding: 50px;
    background: lemonchiffon;
}

 

子組件css

 

 

.son{
    padding: 30px;
    background: lightblue;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM