4、react 父子组件传值

父传子:


3
父组件代码: 4 import React from 'react'; 5 import User from './pages/User' 6 import Search from './pages/Search' 7 8 function App() { 9 10 const context = { 11 userInfo:'小明' 12 } 13 14 return ( 15 <div className="App"> 16 <User context={context}/> 17 <Search context={context}/> 18 </div> 19 ); 20 } 21 22 export default App; 23 24 函数子组件代码: 26 import React,{ useState,useEffect } from 'react' 28 function User(props){ 30 const { userInfo } = props.context; 31 32 return( 33 <React.Fragment> 34 <h1>function{userInfo}</h1> 35 </React.Fragment> 36 ) 37 } 38 39 export default User;

class子组件代码:

import React,{Component} from 'react'

class Search extends Component{
        render() {
            const {userInfo}= this.props.context;
            return(
                <React.Fragment>
                <h1>{userInfo}class组件</h1>
                </React.Fragment>
            )
        }
    }

export default Search;

 如果父组件传递的是函数,则可以把子组件信息传入父组件,这个常称为状态提升,也就是子传父

父组件:

import React from 'react';
import './App.css';
import Search from './pages/Search';


function tellme(msg){
  console.log(msg);
}

function App() { 
  const context = {
    userInfo:'小明'
  }

  return (
    <div className="App">
    <Search context={context}  tellme={tellme}/>
    </div>
  );
}

export default App;


子组件:

import React,{Component} from 'react'

class Search extends Component{
    constructor(props){
        super(props)
        this.state={
            data:'',
            str:''
        }
    }
    
   
        render() {
            const {data,str}= this.state;
           
            return(
                <React.Fragment>
                <button onClick={this.click}>点击</button><input type="text" name="" id="" value={data} onChange={this.Value}/>
                </React.Fragment>
            )
        }
        
        click=()=>{
            const {tellme}= this.props;
            tellme('我是Search');
            console.log(11);
        };
        Value=(e)=>{
            console.log(e.target.value);
            let val = e.target.value
            this.setState({
                data:val
            })
        }
    }

export default Search;

 

posted @ 2020-08-30 23:33  雪糕战士  阅读(347)  评论(0编辑  收藏  举报