父组件传值给子组件
export const Farther = () => {
const msg = "大家好呀";
const value = "I'm JavaScript";
return (
<div>
<span>我是父亲组件</span>
<Son msg={msg} value={value}/>
</div>
)
}
export const Son = (props)=>{
const { value } = props;
return (
<div>
<span>我是孩子组件: 这是我从父组件接收到的值:{props.msg}{value}</span>
</div>
)
}
子组件传值给父组件
import React, { useState} from 'react';
export const Farther = () => {
const [fartherCount, setFartherCountt] = useState<number>(0);
const getSonCount = (val: number) => {
setParentCountt(val);
};
return (
<div>
<span>我是父亲组件</span>
<Son getCount={getSonCount} />
</div>
)
}
export const Son = (props)=>{
const [sonCount, setSonCountt] = useState<number>(9);
const uploadCount = () => {
props.getCount(sonCount);
};
return (
<div>
<button onClick={() => uploadCount()}>点击子组件后传值</button>
</div>
)
}
|