父組件
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
