react函数式组件传值之父传子
具体案例
案例主要实现一个简单的父组件Home向子组件Child传递count值,子组件通过props拿到此值并渲染出来。
父组件:home.tsx
import React, { useState } from 'react';
import './index.less';
import Child from './component/child';
const Home: React.FC = () => {
const [count, setCount] = useState<number>(0);
return (
<div className="home-wrap">
<p>当前数字:{count}</p>
<button
onClick={() => {
setCount(count + 1);
}}
>
数字递增
</button>
<Child count={count} />
</div>
);
};
export default Home;
子组件:child.tsx
import React from 'react';
type selfProps = {
count: number;
};
const Child: React.FC<selfProps> = (props) => {
const { count } = props; //解构赋值
return (
<div className="child-wrap">
<p>子组件</p>
<p>从父组件传下来的数字是:{count}</p>
</div>
);
};
export default Child;
效果展示
END
大前端教程
前端知识每日更新,积少成多,助你轻松学。致力于javascript/css/react/vue/小程序/webpack等前端技术和工具的学习讲解。
Official Account
喜欢本文就点赞分享一下吧,感谢你的支持