我们在引入子组件时,子组件的名字一定要大写,否则会报错(这是个babel编译机制问题)。那么,父组件在引入子组件后,如何传值呢?首先,父组件要将传递的参数写到子组件标签上,然后,子组件通过props接收父组件传过来的所有参数。

组件Home向子组件Child传递count值,子组件通过props拿到此值并渲染出来。

父组件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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;

子组件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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;