跳到主要内容

React

React 组件的定义

React 组件必须以大写字母开头,而 HTML 标签则必须是小写字母。

function MyButton() {
return (
<button>
I'm a button
</button>
);
}

export default function MyApp() {
return (
<div>
<h1>Welcome to my app</h1>
<MyButton />
</div>
);
}

JSX 如果想包裹多个元素,需要使用一个父元素包裹起来,否则会报错

function AboutPage() {
return (
<>
<h1>About</h1>
<p>Hello there.<br />How do you do?</p>
</>
);
}

渲染列表

假设你有一个产品数组:

const products = [
{ title: 'Cabbage', id: 1 },
{ title: 'Garlic', id: 2 },
{ title: 'Apple', id: 3 },
];

在你的组件中,使用 map() 函数将这个数组转换为 <li> 标签构成的列表:

const listItems = products.map(product =>
<li key={product.id}>
{product.title}
</li>
);

return (
<ul>{listItems}</ul>
);