react父子組件傳值方式一之props方法


父組件

import React, { useState, useEffect, memo, useMemo, createContext, useCallback, useReducer, useContext } from 'react';
import Counter from './four';
export function Three(props) {
  const [clval, setClval] = useState(null)
  const getChildrenValue = (value) => {
    console.log('value父', value);
  // 獲取子組件傳過來的value值並設置到clval,val參數就是子組件的value值 setClval(value) }
return ( <div> {clval}
  {/* 這里是重要代碼,向子組件傳遞getValue這個prop,它的值是一個回調函數 */}
<Counter getValue={getChildrenValue}></Counter> </div> ); }
Counter子組件
import React, { useState, createContext, useContext } from 'react';
function Counter(props) {
  const [value, setValue] = useState("我是三級子組件");
  const toparent = () => {
    console.log('我是兒子', props)
  // 向父組件傳遞每次遞增的value值 props.getValue(value) }
return ( <div> 222
  {/* <button onClick={() => toparent()}>我是子組件</button> */}
      <button onClick={toparent}>我是子組件</button>
    </div>
  )
}
export default Counter

 

參考的https://blog.csdn.net/m0_38134431/article/details/118489375


免責聲明!

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



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