React
yuhuo2024-01-28开发库框架库
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello World</title>
<script src="../../static/js/react.development.js"></script>
<script src="../../static/js/react-dom.development.js"></script>
<script src="../../static/js/babel.min.js"></script>
<style>
.title {
color: red;
}
</style>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
// 子组件
function MyButton({ text }) {
console.log("来自父组件:" + text);
// 非响应式
let num = 0;
// 响应式
const [count, setCount] = React.useState(0);
// 定义事件
function addNum() {
num++;
}
function addCount() {
setCount(count + 1);
}
return (
<>
{text}
{/* 只传递事件函数(没有括号) */}
<button onClick={addNum}>num:{num}</button>
<button onClick={addCount}>count:{count}</button>
</>
);
}
// 父组件
function MyApp() {
let text = "标题";
let title = (
/* class 改成 className */
<h1 className="title" style={{ fontSize: "30px" }}>
{"大" + text}
</h1>
);
const products = [
{ title: "Cabbage", isFruit: false, id: 1 },
{ title: "Garlic", isFruit: false, id: 2 },
{ title: "Apple", isFruit: true, id: 3 },
];
return (
<div>
{/* dom可以直接来自上面 */}
{title}
{/* 嵌套子组件 */}
<MyButton text={text} />
{/* 条件渲染 */}
{text == "标题" ? <div>哈哈哈</div> : <div>嘻嘻嘻</div>}
{text && <div>哈哈哈</div>}
{/* 列表渲染 */}
<ul>
{products.map((product) => (
<li
key={product.id}
style={{
color: product.isFruit ? "magenta" : "darkgreen",
}}
>
{product.title}
</li>
))}
</ul>
</div>
);
}
const container = document.getElementById("root");
const root = ReactDOM.createRoot(container);
root.render(<MyApp />);
</script>
</body>
</html>