zoukankan      html  css  js  c++  java
  • 父子组件传值(子组件传递父组件)

    父组件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;
    }
  • 相关阅读:
    敲七
    二维指针数组**p
    食物链(待解决)
    蛇行矩阵
    快速排序 QuickSort
    堆排序
    猪的安家
    百度语言翻译机
    HTML <base> 标签
    免费网络管理流量监控软件大比拼
  • 原文地址:https://www.cnblogs.com/r-mp/p/11218077.html
Copyright © 2011-2022 走看看