Component names must start with a capital letter or they won’t work!
export components的方式有两种:
default export
named exports
一个js文件中只能有一个default export,但可以有多个named exports。
同时在其他文件进行import的时候也有差别:
Syntax | Export statement | Import statement |
---|---|---|
Default | export default function Button() {} |
import Button from './Button.js'; |
Named | export function Button() {} |
import { Button } from './Button.js'; |
JSX is a syntax extension for JavaScript that lets you write HTML-like markup inside a JavaScript file.
Each React component is a JavaScript function that may contain some markup that React renders into the browser. React components use a syntax extension called JSX to represent that markup. JSX looks a lot like HTML, but it is a bit stricter and can display dynamic information.
{}
用于变量或者函数的引入。
如果要将对象作为参数传递,需要使用double curlies
。
person=
。
在css中,也需要这样使用:
1
<ul style=>
React components use props to communicate with each other. Every parent component can pass some information to its child components by giving them props. Props might remind you of HTML attributes, but you can pass any JavaScript value through them, including objects, arrays, and functions.
component可以直接用{}接受参数传递。
1
2
3
function Avatar({ person, size }) {
// ...
}
同样的,如果参数多了,也可以用props
来作为对象接受所有的参数。
1
2
3
4
5
6
7
8
9
10
function Avatar(props) {
let person = props.person;
let size = props.size;
// ...
}
// Specifying a default value for a prop
function Avatar({ person, size = 100 }) {
// ...
}
有时候为了简洁性,会直接用spread syntax转发props。
1
2
3
4
5
6
7
function Profile(props) {
return (
<div className="card">
<Avatar {...props} />
</div>
);
}
When you nest content inside a JSX tag, the parent component will receive that content in a prop called children
. For example, the Card
component below will receive a children
prop set to <Avatar />
and render it in a wrapper div:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import Avatar from './Avatar.js';
function Card({ children }) {
return (
<div className="card">
{children}
</div>
);
}
export default function Profile() {
return (
<Card>
<Avatar
size={100}
person=
/>
</Card>
);
}
function Avatar({ person, size })
destructuring syntax.size = 100
, which is used for missing and undefined
props.<Avatar {...props} />
JSX spread syntax, but don’t overuse it!<Card><Avatar /></Card>
will appear as Card
component’s children
prop.主要的点就两点:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { recipes } from './data.js';
export default function RecipeList() {
const cc = recipes.map(recipe =>
<div key={recipe.id}>
<h2>{recipe.name}</h2>
<ul>
{recipe.ingredients.map(ingredient =>
<li key={ingredient}>
{ingredient}
</li>
)}
</ul>
</div>
)
return (
<div>
<h1>Recipes</h1>
{cc}
</div>
);
}