【React】react學習筆記10-兄弟組件間的傳值


  上一篇博文簡述了腳手架的使用,以及在ws中的簡單配置,詳細的配置方法就不講了,可能有很多細節,在日常使用中發掘就好。然后是腳手架的項目結構以及之間的聯系,這個完全可以自己找出來,再不濟就百度一下就好。

  今天記錄一下組件之間的傳值問題,特別是兄弟組件的傳值,真的是為難了我好久的一個問題:

 

要做啥呢?:

方便兄弟組件中傳值,我知道的實現方式有兩種,一種是使用React Context,一種是 如圖所示的傳球:

 

 

組件結構圖:

輸入參數,點擊查詢,查詢的input值傳遞給兄弟組件查詢數據:

 

 

組件代碼: 

父組件:

import React,{Component} from 'react';
import Label from './Label';
import Search from './Search';
//組件傳值可以使用 Context
export default class ChatCir extends Component{
    constructor(props){
        super(props);
        this.state={
            keyWord: ''
        }
    }
    //設置組件A input的查詢參數
    setKeyWorld = (keyWord) => {
        this.setState({
            keyWord
        })
    }

    render() {
        return (
            <div>
                {/*組件A*/}
                <Search setKeyWorld={this.setKeyWorld} />
                {/*組件B*/}
                <Label keyWordValue={this.state.keyWord}/>
            </div>

        );
    }

}

 

組件A:

import React,{Component} from 'react';

export default class Search extends Component{
    constructor(props){
        super(props);
        this.state={
            currentKeyValue: ''
        }
    }
    setCurrentKeyValue= (e) => {
        const currentKeyValue = e.target.value
        this.setState({
            currentKeyValue
        })

    }
    //點擊查詢按鈕,將值傳給父組件
    search = () =>{
        this.props.setKeyWorld(this.state.currentKeyValue);
    }
    render() {
        return (
            <div>
                <input type="text" value={this.state.currentKeyValue} onChange={this.setCurrentKeyValue}/>
                <button onClick={this.search}>查詢</button>
            </div>
        );
    }

}

 

組件B:

import React,{Component} from 'react';
import axios from 'axios';
//項目目錄執行
//npm isntall axios --save
//npm i -S axios

export default class Label extends Component{
    constructor(props){
        super(props);
        this.state={
            key: '',
            UserList: []
        }
    }


    //props將要被改變前執行
    componentWillReceiveProps(props){

        const key=props.keyWordValue;
        console.log('key',key)
        this.setState({key});
        //ajax請求接口
        axios.get('https://api.github.com/search/users?q='+key)
            .then(response=>{
                const {items} =  response.data;
                console.log(items)
                this.setState({UserList: items})

            })
            .catch( error=> {
                console.log(error);
            })
    }

    render() {
        const UserList=this.state.UserList;
        // 遍歷列表數據
        return UserList.map((value,index)=> (
            <div style={{width: 110, height:160,float:'left'}}>
                <img style={{width: 100, height:100}} src={value.avatar_url} alt=""/>
                <p>用戶Id:{value.login}</p>
            </div>
        ));
    }

}

 


免責聲明!

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



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