jsx语法规则:
1.定义虚拟DOM时,不要写引号。
2.标签中混入JS表达式时要用{}。
3.样式的类名指定不要用class,要用className。
4.内联样式,要用style={{key:value}}的形式去写。
5.只有一个根标签
6.标签必须闭合
7.标签首字母
(1).若小写字母开头,则将该标签转为html中同名元素,若html中无该标签对应的同名元素,则报错。
(2).若大写字母开头,react就去渲染对应的组件,若组件没有定义,则报错。
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
.hello {
width: 200px;
height: 200px;
background-color: rgb(231, 244, 250);
line-height: 200px;
text-align: center;
}
</style>
<body>
<div id="hello"></div>
</body>
<!-- 引入react核心库 -->
<script type="text/javascript" src="../js/react.development.js"></script>
<!-- 引入react-dom,用于支持react操作DOM -->
<script type="text/javascript" src="../js/react-dom.development.js"></script>
<!-- 引入babel,用于将jsx转为js -->
<script type="text/javascript" src="../js/babel.min.js"></script>
<script type="text/babel"> /* 此处一定要写babel */
const name = "张三";
const old=18;
//1.创建虚拟DOM
const VDOM = <div className="hello">我叫{name},今年{old}岁!</div> /* 此处一定不要写引号,因为不是字符串 */
//2.渲染虚拟DOM到页面
ReactDOM.render(VDOM, document.getElementById('hello'))
</script>
</html>
二、通过数组建立虚拟dom
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
.hello {
width: 200px;
height: 200px;
background-color: rgb(231, 244, 250);
/* line-height: 200px; */
text-align: center;
overflow: hidden;
}
</style>
<body>
<div id="hello"></div>
</body>
<!-- 引入react核心库 -->
<script type="text/javascript" src="../js/react.development.js"></script>
<!-- 引入react-dom,用于支持react操作DOM -->
<script type="text/javascript" src="../js/react-dom.development.js"></script>
<!-- 引入babel,用于将jsx转为js -->
<script type="text/javascript" src="../js/babel.min.js"></script>
<script type="text/babel"> /* 此处一定要写babel */
const info = ["张三", 18, "男"];
//1.创建虚拟DOM
const VDOM = (
<div className="hello">
<h3>学生信息</h3>
{
info.map((item)=>{
return <div style={{fontSize:'18px',height:"30px"}}> {item}</div>
})
}
</div>
)
//2.渲染虚拟DOM到页面
ReactDOM.render(VDOM, document.getElementById('hello'))
</script>
</html>