先上个简单的react例子叭~~
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<!-- 引入react核心库 -->
<script src="./js/react.development.js"></script>
<!-- 引入react-dom,用于支持react操作DOM -->
<script src="./js/react-dom.development.js"></script>
<!-- 引入babel,用于将jsx转为js -->
<script src="./js/babel.min.js"></script>
<script type="text/babel">
// 1.创建虚拟DOM
const VDOM = (
<h1>
<span>hello react</span>
</h1>
);//此处不要写引号,因为不是字符串
// 2.渲染虚拟DOM到页面
ReactDOM.render(VDOM,document.getElementById('test'));
</script>
</head>
<body>
<!-- 准备好一个容器 -->
<div id="test"></div>
</body>
</html>
1.定义虚拟DOM时,不用写引号
// 1.创建虚拟DOM
const VDOM = (
<h1>
<span>hello react</span>
</h1>
);//此处不要写引号,因为不是字符串
2.标签中混入JS表达式时使用{}
使用js变量怎么输出呢?
const myId = 'wOrld';
const myData = 'hEllO,wOrld';
//1.创建虚拟DOM
const VDOM = (
<h1 id={myId.toUpperCase()}>
<span>{myData.toLowerCase()}</span>
</h1>
3.样式的类名指定不要用class,要用className
搞一个样式~~
<style>
.title{
background-color:#bfa;
}
</style>
把class添加进去,注意:往标签添加样式的类名为className而不是class
//1.创建虚拟DOM
const VDOM = (
<h1 className="title" id={myId.toUpperCase()}>
<span >{myData.toLowerCase()}</span>
</h1>
);
4.内联样式,要用style={{key:value}}的形式去写
//1.创建虚拟DOM
const VDOM = (
<h1 className="title" id={myId.toUpperCase()}>
<span style={{color: 'white', fontSize:"33px"}}>{myData.toLowerCase()}</span>
</h1>
5.只有一个根标签
//1.创建虚拟DOM
const VDOM = (
<h1 className="title" id={myId.toUpperCase()}>
<span style={{color: 'white', fontSize:"33px"}}>{myData.toLowerCase()}</span>
</h1>
<h1>
</h1>
);
解决方法:在外面嵌套一个根标签,例如div
//1.创建虚拟DOM
const VDOM = (
<div>
<h1 className="title" id={myId.toUpperCase()}>
<span style={{color: 'white', fontSize:"33px"}}>{myData.toLowerCase()}</span>
</h1>
</div>
);
6.标签必须闭合
//1.创建虚拟DOM
const VDOM = (
<h1 className="title" id={myId.toUpperCase()}>
<span style={{color: 'white', fontSize:"33px"}}>{myData.toLowerCase()}</span>
</h1>
<input type="text">
);
解决方法:标签必须闭合
//1.创建虚拟DOM
const VDOM = (
<div>
<h1 className="title" id={myId.toUpperCase()}>
<span style={{color: 'white', fontSize:"33px"}}>{myData.toLowerCase()}</span>
</h1>
<input type="text"></input >
</div>
);
7.标签首字母
(1)若小写字母开头,则将该标签转为html中同名元素,若html中无该标签对应的同名元素,则报错
<good>abc</good>
!
(2)若大写字母开头,react就去渲染对应的组件,若组件没有定义,则报错
<Good>abc</Good>