- 数据绑定:我们在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来做判断。