react文档阅读

This commit is contained in:
2023-05-25 00:58:49 +08:00
parent 5e84650984
commit 44f37fc0ff

View File

@@ -219,6 +219,64 @@ function MyButton({ count, onClick }) {
}
```
此时由MyApp传递给MyButton的值称之为prop
## jsx展开传递props
如果父组件想要将接收到的props全部传递给子组件无需在子组件上列出props中全部属性可以使用`...props`来进行展开
```js
function Profile(props) {
return (
<div className="card">
<Avatar {...props} />
</div>
);
}
```
## 将jsx作为子组件传递
当采用如下形式时:
```js
<Card>
<Avatar />
</Card>
```
其中父组件接收到的prop中children将代表接受到的子组件内容
```js
import Avatar from './Avatar.js';
function Card({ children }) {
return (
<div className="card">
{children}
</div>
);
}
export default function Profile() {
return (
<Card>
<Avatar
size={100}
person={{
name: 'Katsuko Saruhashi',
imageId: 'YfeOqp2'
}}
/>
</Card>
);
}
```
此时想要嵌套在父组件内部的子组件可以通过props.children来访问。
## 条件渲染
如果在某些条件下组件不想显示任何内容可以返回null
```js
function Item({ name, isPacked }) {
if (isPacked) {
return null;
}
return <li className="item">{name}</li>;
}
```