02了解JSX语法

  1. 数据绑定:我们在js中写html代码,在html代码中可以使用大括号{}包括写js表达式,例如:
let user = "方华永";
let age = 18;

// javascript XML
const template = (<div>
        <p>我的名字是 {user}</p>
        <h3>今天有{age + 2}</h3>
    </div>)

// 获取html文件中的节点,使用ReactDOM中的render方法插入
const root = document.getElementById("app");
ReactDOM.render(template, root)

在这里插方方入图片描述
2. 在js表达式中可以写条件渲染,可以使用三种方法:
函数 if语句

const showLocation = () => {
    return "云南"
}

// javascript XML
const template = (<div>
        <p>家乡在 {showLocation()}</p>
    </div>)

在这里插入图片描述

const user = {
    name: "方华永",
    age: 18,
    location: "云南"
}

const showLocation = (location) => {
    if(location){
        return location;
    }
    return "北京"
}

// javascript XML
const template = (<div>
        <p>我的名字是 {user.name}</p>
        <h3>今天有{user.age + 2}</h3>
        <p>家乡在 {showLocation()}</p>
        <p>家乡在 {showLocation(user.location)}</p>
    </div>)

// 获取html文件中的节点,使用ReactDOM中的render方法插入
const root = document.getElementById("app");
ReactDOM.render(template, root)

在这里插入图片描述
也可以直接return html标签

const user = {
    name: "方华永",
    age: 18,
    location: "云南"
}

const showLocation = (location) => {
    if(location){
        return <p>家乡在 {location}</p>;
    }
}

// javascript XML
const template = (<div>
        <p>我的名字是 {user.name}</p>
        <h3>今天有{user.age + 2}</h3>
        {showLocation(user.location)}
    </div>)

在这里插入图片描述
三目运算符:

const user = {
    name: "方华永",
    age: 18,
    location: "云南"
}
const user1 = {
    age: 20,
    location: "山东"
}
const showLocation = (location) => {
    if(location){
        return <p>家乡在 {location}</p>;
    }
}

// javascript XML
const template = (<div>
        <p>{user.name ? "我的名字是" + user.name : "游客"}</p>
        <p>{user1.name ? "我的名字是" + user1.name : "游客"}</p>
    </div>)

在这里插入图片描述
逻辑运算符 &&
true false null undefined 都不会在表达式中显示

const user = {
    name: "方华永",
    age: 15,
    location: "云南"
}
const user1 = {
    age: 20,
    location: "山东"
}
// javascript XML
const template = (<div>
        {user.age >= 18 && <p>年龄:{user.age}</p>}
        {user1.age >= 18 && <p>年龄:{user1.age}</p>}
    </div>)

在这里插入图片描述
条件不满足的没有显示。
数组可以用length来做判断。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值