React父子組件傳值


  父組件向子組件傳值使用props,子組件向父組件傳值通過觸發方法來傳值。具體栗子如下。

一、創建父組件index

import React, { useState } from "react";
import { Input } from 'antd'
import ChildComponent from "./ChildComponent"; 
export default () => {
  const [inputValue1, setInputValue] = useState<string>('傳遞的第一個參數')
  return (
    <div>
      <div>
        <h2>父組件</h2>
        <Input style={{ width: '200px' }} placeholder='請輸入內容' value={inputValue1} onChange={(e) => setInputValue(e.target.value)} />
      </div>
      <ChildComponent inputValue1={inputValue1}/>  //向子組件傳遞了一個inputValue1
   </div>
  );
};

二、創建子組件ChildComponent

import React, { useState } from "react";
import { Button } from "antd";
export default (props: any) => {
  return (
    <div>
      <h2>子組件</h2>
      <p>inputValue1:{props.inputValue1}</p>  //通過props拿到了父組件傳遞的inputValue1
    </div>
  );
};

三、父組件向子組件傳值

  父組件向子組件傳值時,先將需要傳遞的值傳遞給子組件,然后在子組件中,使用props來接收父組件傳遞過來的值,具體的可看創建父子組件的代碼。

  父組件將inputValue1傳遞給子組件:

<ChildComponent inputValue1={inputValue1} />

  子組件通過props接收inputValue1:

<p>inputValue1:{props.inputValue1}</p>

  這樣在父組件的input改變時,子組件通過props獲取的inputValue1也會實時改變。如:在父組件輸入框輸入“改變了父組件”,子組件也變成了“改變了父組件”。這樣一個父組件向子組件傳值就完成了。

  

 

 四、子組件向父組件傳值

  子組件向父組件傳值時,需要通過觸發方法來傳遞給父組件

  父組件定義一個方法:

<ChildComponent inputValue1={inputValue1} childClick={childClickFunc} />     //定義一個childClickFunc方法
const childClickFunc = (value: any) => {
    //通過觸發方法改變父組件的值 value即為子組件傳遞給父組件的值
    setInputValue(value) 
  }

  子組件觸發父組件方法:

<Button onClick={() => props.childClick('子組件改變父組件的inputValue')}>點擊改變父組件的值</Button> //通過props觸發父組件傳遞的方法

 點擊Button按鈕后,觸發父組件方法,父子組件的值都更改為“子組件改變父組件的inputValue”,這樣子組件向父組件傳值就完成了。

 

 

 五、父組件向子組件傳遞多個值的寫法

  父組件需要向子組件傳遞多個值,比如inputValue1,inputValue2,inputValue3.......

  方法1:

<ChildComponent inputValue1={inputValue1} inputValue2={inputValue2} inputValue3={inputValue3} childClick={childClickFunc} />

  方法2:

<ChildComponent {...{ inputValue1, inputValue2, inputValue3 }} childClick={childClickFunc} />

  兩種寫法都可進行傳值,只是第二種比較簡潔。

  


免責聲明!

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



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