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;
    }
  • 相关阅读:
    TestNG 入门教程
    Angularjs中文版本开发指南发布
    你是码农 还是优秀程序员?
    java牛人给新人的几点建议
    有一种毒药叫励志书
    牛人眼中如何精通spring?
    驯服你的Windows Server 2003
    windows 7 里面的iis在哪里
    神器 cmder
    亚信UED前端流程自动化构建工具
  • 原文地址:https://www.cnblogs.com/r-mp/p/11218077.html
Copyright © 2011-2022 走看看