认识JSX
JSX语法
简单来说就是用js代码中混入了html,js代码的写法
html标签表示
jsx中html代码直接使用正常的html标签即可,与原生的没有区别
<h1>hello word</h1>
组件表示
jsx中组件默认是大写字母开头的,而小写字母开头的默认为html标签
// html标签表示
<h1>hello word</h1>
// 组件表示一
<Demo></Demo>
// 组件表示二
<Demo />
注意组件需要保证是单根节点,如果你不希望多出一个无用的节点可以使用
<></>, 详细可以查看Fragments
变量表示
jsx中变量使用{}包裹
// 写法一
const text = "hello world"
<h1>{text}</h1>
// 写法二
const textFn = () => "hello word"
<h2>{textFn()}</h2>
// 写法三
const textParamsFn = (t) => t + " 哈哈"
<h3>{textParamsFn("test")}</h3>
// 写法四
const flag = true;
const haha = "哈哈哈";
const xixi = "嘻嘻";
<h3>{flag ? haha : xixi}</h3>
行内样式表示
jsx中的属性,主要还是使用变量的方式,但是记住了,style属性是一个对象
<h1 style={{color: "red"}}>{text}</h1>
注意这里有两层
{}
- 第一层表示的是这个内容是变量
- 第二层表示这个变量是一个对象
同下
let style = {color: "red"};
<h1 style={style}>{text}</h1>
html中的class表示
为什么要单独拿出来讲一下这个属性呢?因为有所不同。jsx本质上是js语法,但是class已经是js中的关键字,为了避免冲突与误会,所以在jsx中class改为了className,以上是我的理解^_^,当然我的理解不重要,哈哈哈。其实官方团队好像有回应可以查看,下面还有原地址可以看,只是被墙了有趣的话题,为什么jsx用className而不是class
// 写法一
<h1 className="title">hello word</h1>
// 写法二
let flag = true;
let active = "active-info";
let blur = "no-active-info";
<h1 className={flag ? active : blur}>hello word</h1>
事件表示
jsx中的事件表示方式和原生的是差不多了,只是原生的使用的是全小写,jsx中使用的是驼峰
// 写法一
<h1 onClick={() => {console.log("哈哈哈")}}>hello word</h1>
// 写法二
const log = () => {console.log("xixixi")}
<h1 onClick={log}>hello word</h1>
// 写法三
function logFn(){
console.log("xixi哈哈哈")
}
<h1 onClick={logFn}>hello word</h1>
问题: jsx文件最后会变成什么呢?
我们看到jsx中的表示很新颖,但也不难理解,但是浏览器肯定不会认这种内容的,所以我们还需要将jsx转化为浏览器认识的东西,这个时候就需要提到babel了,babel可以将jsx转化为浏览器能认识的东西,我们可以通过这个地址jsx在线转化查看到底转成了什么
标签版
原jsx代码
<h1 className='title' style={{ color: "red" }} onClick={() => {console.log("哈哈哈")}}>
hello <span>word</span>
</h1>
转化后代码
React.createElement("h1", {
className: "title",
style: {
color: "red"
},
onClick: () => {
console.log("哈哈哈");
}
}, "hello ", /*#__PURE__*/React.createElement("span", null, "word"));
组件版
原jsx代码
function HelloWord({text}){
return <h1 className='title' style={{ color: "red" }} onClick={() => {console.log("哈哈哈")}}>hello1 <span>word</span> {text}</h1>
}
function Demo() {
let a = "test";
return <HelloWord text={a}/>
}
转化后代码
function HelloWord({
text
}) {
return /*#__PURE__*/React.createElement("h1", {
className: "title",
style: {
color: "red"
},
onClick: () => {
console.log("哈哈哈");
}
}, "hello1 ", /*#__PURE__*/React.createElement("span", null, "word"), " ", text);
}
function Demo() {
let a = "test";
return /*#__PURE__*/React.createElement(HelloWord, {
text: a
});
}
这个代码浏览器基本就可以认识了,但是还有一点不认识的就是这个
React.createElement,但是这个不急,我们后面慢慢看