const h1 = (<h1>Hello World <span>一个span元素</span></h1>)
会被编译成
const h1 = React.createElement("h1",
{
},
'Hello World',
React.createElement("span", {
}, '一个span元素')
)
但是如果这么写,就有两个根节点,无法编译,因为React.createElement
只能创建一个根节点
const h1 = (
<h1>Hello World <span>span元素</span></h1>
<p>asdfafdafd</p>
)
如果你非要这么写,你可以在外面用
给他包裹起来,如果不想有真实的节点,那就
<>>
这么写,总之,就是必须要有根节点
<>>
其实是语法糖,真实的样子是这样的
const img = (
<img src="https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2962719555,3613138778&fm=27&gp=0.jpg" alt="" />
//
);
ReactDOM.render(img, document.getElementById('root'));
{/* */}
const a=1234,b=4321;
const div = (<div>{
a}*{
b}={
a * b}</div>)
//const div = React.createElement('div', {}, `${a}*${b}=${a * b}`)
ReactDOM.render(div, document.getElementById('root'));
- null
、undefined
、false
不会显示,0
可以
const div = (
<div>
<p>`null`、`undefined`、`false`不会显示,`0`可以</p>
<p>{
null}</p>
<p>{
false}</p>
<p>{
undefined}</p>
<p>{
0}</p>
</div>
)
const obj = {
name: '张三',
age: '18'
}
const div = (
<div>{
obj}</div>
)
const url = "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2962719555,3613138778&fm=27&gp=0.jpg";
const cls = "image";
const div = (
<div>
<img src={
url} className={
cls} style={
{
marginLeft: "50px",
width: "200px"
}} alt="" />
</div>
);
ReactDOM.render(div, document.getElementById("root"));
const content = "afasfasfd
阿斯顿法定发送
";
const div = (
<div>{
content}
</div>
);
ReactDOM.render(div, document.getElementById("root"));
const content = "afasfasfd
阿斯顿法定发送
";
const div = (
<div dangerouslySetInnerHTML={
{
__html: content
}}>
</div>
);
ReactDOM.render(div, document.getElementById("root"));
let num = 0;
const div = (
<div>{
num}
</div>
);
console.log(div)
div.props.children = 1
ReactDOM.render(div, document.getElementById("root"));