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


父組件js

 

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

class Father extends Component {
    constructor(props) {
        super(props);
        this.state = {
            inputVal: '',
            tmp: ''
        }
    }
    
    render() {

        let value = 4131783;
        let {inputVal} = this.state;

        return (
            <div className="father">
                <h1>我是父組件</h1>
                <input type="text" value={inputVal} onChange={this.inputChangeAction}/>
                <button onClick={this.sendAction}>發送</button>

                <Son title="hello react" val={value} inputValue={this.state.tmp}/>

            </div>
        );
    }

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

    sendAction = ()=>{
        //輸入框的值  this.state.inputVal
        this.setState({tmp: this.state.inputVal});

    }
}

export default Father;

 

父組件css

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

子組件js

 

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

class Son extends Component {
    // this.props.xxx   外部調用組件時,傳入組件的屬性,只能使用,不能修改。數據單向自頂向下傳遞的
    // this.state.xxx   內部的狀態,內部狀態可以使用也可以修改
    render() {

        console.log(this.props.title);

        return (
            <div className="son">
                <h1>我是子組件</h1>
                <p>接收到的title值為:{this.props.title}</p>
                <p>接收到的val值為:{this.props.val}</p>
                <p>接收到的inputValue值為:{this.props.inputValue}</p>
            </div>
        );
    }
}

export default Son;

 

子組件css

 

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

 


免責聲明!

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



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