在用react进行函数式编程时,父组件可以通过props向子组件传值,那么子组件怎么向父组件传值呢?首先,父组件需要向子组件传递一个函数,然后,子组件通过props获取函数并附上参数,最后,父组件通过函数拿到子组件传递的值。
一、具体案例
父组件:home.tsx
import React, { useState } from 'react';
import Child from './component/child';
import './index.less';
const Home: React.FC = () => {
const [parentCount, setParentCountt] = useState<number>(0);
const getChildCount = (val: number) => {
setParentCountt(val);
};
return (
<div className="home-wrap">
<p>我是父组件</p>
<p>子组件传过来的数字:{parentCount}</p>
<Child getCount={getChildCount} />
</div>
);
};
export default Home;
子组件:child.tsx
import React, { useState } from 'react';
type selfProps = {
getCount: Function;
};
const Child: React.FC<selfProps> = (props) => {
const { getCount } = props;
const [count, setCount] = useState<number>(0);
const addCount = (val: number) => {
setCount(val);
getCount(val);
};
return (
<div className="child-wrap">
<p>子组件</p>
<p>数字:{count}</p>
<button onClick={() => addCount(count + 1)}>数字递增</button>
</div>
);
};
export default Child;
二、效果展示
【关联文章】
react函数式组件传值之父传子https://blog.csdn.net/w544924116/article/details/119464737
感谢您读完本文!如果本文对您有帮助,请点个赞呗,您的点赞是对我最大的支持和认可!
我的公众号:大前端教程,欢迎关注,会定期更新前端知识,希望能帮到您。