React & JSX 入门
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="react-container">
</div>
<script src="https://unpkg.com/react@15.4.2/dist/react.js"></script>
<script src="https://unpkg.com/react-dom@15.4.2/dist/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.29/browser.js"></script>
<script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<script type="text/babel">
//在这里编写JSX代码, 或者链接其他包含JSX代码的独立JavaScript文件
/*----------------------------------------------------------*/
//菜谱对象数组
let data = [
{
"name": "Baked Salmon",
"ingredients": [
{"name": "Salmon", "amount": 1, "measurement": "1 lb"},
{"name": "Pine Nuts", "amount": 1, "measurement": "cup"}
],
"steps": [
"Preheat the oven to 350 degrees.",
"Spread the olive oil around a glass baking dish."
]
}
];
//单个菜谱的无状态函数式组件
const Recipe = (props) => {
return (
<section id={props.name.toLowerCase().replace(/ /g, "-")}>
<h1>{props.name}</h1>
<ul>
{props.ingredients.map((ingredient, i) =>{
return (
<li key={i}>{ingredient.name}</li>
)
})}
</ul>
<section>
<h2>Cooking Instructions</h2>
{props.steps.map((step, i) =>
<p key={i}>{step}</p>
)}
</section>
</section>
)
}
//菜谱菜单的无状态函数式组件
const Menu1 = (props) => {
return <article>
<header>
<h1>{props.title}</h1>
</header>
<div>
{props.recipes.map((recipe, i) => {
return <Recipe
key={i}
name={recipe.name}
ingredients={recipe.ingredients}
steps={recipe.steps}
/>
})}
</div>
</article>
}
const Menu2 = ({title, recipes}) => (
<article>
<header>
<h1>{props.title}</h1>
</header>
<div>
{props.recipes.map((recipe, i) =>
<article>
<header>
<h1>{title}</h1>
<div>
{recipes.map((recipe, i) =>
<Recipe key={i} {...recipe}/>
)}
</div>
</header>
</article>
)}
</div>
</article>
)
//调用ReactDOM.render将菜单菜谱渲染到当期DOM上
ReactDOM.render(
<Menu1 recipes={data} title="Delicious Recipes"/>,
document.getElementById("react-container")
)
</script>
</body>
</html>