jsx 是一种 JavaScript 的语法扩展(eXtension),有时候也叫做 JavaScript XML,它能让我们可以在 js 中编写 html
render() {
return (
<div>
{/* 注释 */}
<h2>Hello World</h2>
</div>
)
}
注意:若字符串为 html 代码的话,那么默认会将其以字符串的形式展示
<script type="text/babel">
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
name: '小冯',
age: 18,
arr: ['f', 'y', 'x'],
flag: false,
obj: {
name: '张三',
age: 20
}
}
}
render() {
return (
<div>
<h2>{this.state.name}</h2>
<h2>{this.state.age}</h2>
<h2>{this.state.arr}</h2>
<h2>{this.state.flag ? "你好啊" : null}</h2>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById("app"));
</script>
render() {
return (
<div>
<h2>{4.5 + 4.5}</h2>
<h2>{'f' + 'y'}</h2>
<h2>{true ? '哈哈' : '呵呵'}</h2>
<h2>{() => {return 'hello'}}</h2>
</div>
)
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
title: "标题",
imgUrl: "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1596216948746&di=24fe98fbd1f1f6fb54a6f9b86bc36d28&imgtype=0&src=http%3A%2F%2Fa1.att.hudong.com%2F62%2F02%2F01300542526392139955025309984.jpg",
link: "http://www.baidu.com",
active: true
}
}
render() {
const { title, imgUrl, link, active } = this.state;
return (
<div>
{/* 1.绑定普通属性 */}
<h2 title={title}>我是标题</h2>
<img src={imgUrl} alt=""/>
<a href={link} target="_blank">百度一下</a>
{/* 2.绑定class */}
<div className="box title">我是div元素</div>
<div className={"box title " + (active ? "active": "")}>我也是div元素</div>
<label htmlFor=""></label>
{/* 3.绑定style */}
<div style={{color: "red", fontSize: "50px"}}>我是div,绑定style属性</div>
</div>
)
}
}
注意
实际上,jsx 只是 React.createElement(component, props, …children) 函数的语法糖
所有的jsx最终都会被转换成React.createElement的函数调用
createElement需要传递三个参数:
<script>
// jsx -> babel -> React.createElement()
const message1 = <h2>Hello React</h2>;
const message2 = React.createElement("h2", null, "Hello React");
ReactDOM.render(message1, document.getElementById("app"));
</script>
可以将写好的 jsx 代码通过 babel 进行编译 传送门