jsx是什么?
1.jsx是一種JavaScript的語(yǔ)法擴(kuò)展(eXtension),也在很多地方稱為JavaScript XML。
2.它用于描述我們的UI界面,并且其完全可以和JavaScript融合使用。
3.它不同于Vue的模塊語(yǔ)法,你不需要專門學(xué)習(xí)模塊語(yǔ)法中的一些指令。jsx中的注釋:
{/*要注釋的內(nèi)容*/}
-
jsx嵌入變量
情況一:當(dāng)變量是Number、String、Array類型時(shí),可以直接顯示;
情況二:當(dāng)變量時(shí)null、undefined、Boolean類型時(shí),內(nèi)容為空;(如果希望可以顯示null、undefined、Boolean,那么需要轉(zhuǎn)成字符串;轉(zhuǎn)換的方式有:toString方法、空字符串拼接、String(變量)等方式;)
情況三:對(duì)象類型不能作為子元素
<body>
<div id="app"></div>
<script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script type="text/babel"> //這里type="text/babel"不能省略,否則無(wú)法使用jsx
class App extends React.Component{
constructor(props){
super(props);
this.state = {
//1.在{}中可以正常顯示顯示的內(nèi)容
name: "mike", //string
age: 18, //number
names: ["cba","nba","wba"], //Array
//2.在{}中不能顯示(忽略)
test1: null,
test2: undefined,
test3: true,
flag: false
}
}
render(){
return (
<div>
<h2>{this.state.name}</h2> //顯示mike
<h2>{this.state.age}</h2> //顯示18
<h2>{this.state.names}</h2> //顯示cbanbawba
<h2>{this.state.test1}</h2> //不顯示
<h2>{this.state.test2}</h2> //不顯示
<h2>{this.state.test3.toString()}</h2> //顯示true
<h2>{this.state.flag + ''}</h2> //顯示false
<h2>{this.state.flag && "good"}</h2> //不顯示
</div>
)
}
}
ReactDOM.render(<App/>,document.getElementById("app"));
</script>
</body>
- jsx嵌入表達(dá)式
運(yùn)算表達(dá)式、三元運(yùn)算符、執(zhí)行一個(gè)函數(shù)
<body>
<div id="app"></div>
<script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script type="text/babel"> //這里type="text/babel"不能省略,否則無(wú)法使用jsx
class App extends React.Component{
constructor(props){
super(props);
this.state = {
firstname: "kobe",
lastname: "bryant",
isLogin: true
}
}
render(){
const {firstname,lastname,isLogin} = this.state;
return (
<div>
{/*1.運(yùn)算符表達(dá)式*/}
<h2>{firstname + " " + lastname}</h2>
<h2>{20 * 50}</h2>
{/*2.三元表達(dá)式*/}
<h2>{isLogin ? "歡迎回來(lái)" : "請(qǐng)先登錄"}</h2>
{/*3.進(jìn)行函數(shù)調(diào)用*/}
<h2>{this.getFullName()}</h2>
</div>
)
}
getFullName() {
return this.state.firstname + " " + this.state.lastname;
}
}
ReactDOM.render(<App/>,document.getElementById("app"));
</script>
</body>
- jsx本質(zhì)
jsx只是React.createElement(component,props,children)函數(shù)的語(yǔ)法糖。