父子组件传值(父组件传递子组件)

父组件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;
}
原文地址:https://www.cnblogs.com/r-mp/p/11218053.html