标签:ret font div color ssi 代码 img turn i++
JSX javascript+html 一种把js和html混合书写的语法,这种语法浏览器不支持,最终会通过babeljs转译成creatElememnt语法,React.createElement("h1", null, "hello"); let ele1 = <h1>hello</h1>
import React from ‘react‘;
import ReactDOM from ‘react-dom‘;
//JSX javascript+html 一种把js和html混合书写的语法,这种语法浏览器不支持,最终会通过babeljs转译成creatElememnt语法,React.createElement("h1", null, "hello");
let ele1 = <h1>hello</h1>
//在babel转义的时候会把ele1转成ele2
// debugger
let ele2 = React.createElement("h1", null, "hello")
console.log(ele2)
ReactDOM.render(
<h1>hello</h1>,
document.getElementById(‘root‘)
);
let ele1 = <h1
id="hello"
className="title">hello</h1>
//在babel转义的时候会把ele1转成ele2
// debugger
// let ele2 = React.createElement("h1", null, "hello")
console.log(ele1) //{type:‘h1‘,props: {id: "hello", className: "title", children: "hello"}}
ReactDOM.render(
ele1,
document.getElementById(‘root‘)
);
function greeting(name) {
return(
<div>hello {name}</div>
)
}
let ele = greeting(‘leah‘)
ReactDOM.render(ele,document.getElementById(‘root‘))
二:循环数组
let arr=[‘1‘, ‘2‘, ‘3‘]
let res = []
for(let i = 0; i <arr.length; i++){
res.push(<li key={i}>{arr[i]}</li>) //创建li元素
}
//将li元素进行渲染
ReactDOM.render(<ul >{res}</ul>,document.getElementById(‘root‘))
三:React.Children.map方法
let ele = (
<div>
<span>1</span>
<span>2</span>
<span>3</span>
</div>
)
ReactDOM.render(<div>{ele}</div>,document.getElementById(‘root‘))
现在想把每一项span用一个div包裹起来,就可以用React.Children.map方法
let spans = [
<span>1</span>,
<span>2</span>,
<span>3</span>
]
let divs = React.Children.map(spans,(item,index) => <div key={index}>{item}</div>)
ReactDOM.render(<div>{divs}</div>,document.getElementById(‘root‘))
四、元素的更新:
每隔一秒返回一个新的时间
let ele = <div>{new Date().toLocaleString()}</div>
setInterval(() => {
ele.props.children = new Date().toLocaleString()
ReactDOM.render(ele,document.getElementById(‘root‘))
}, 1000);
这段代码会报错:TypeError: Cannot assign to read only property ‘children‘ of object ‘#<Object>‘
意思是React元素的属性是不可改的,如果需要修改每次都需要创建一个新的元素,所以需要做如下修改
setInterval(() => {
let ele = <div>{new Date().toLocaleString()}</div>
ReactDOM.render(ele,document.getElementById(‘root‘))
}, 1000);
源码里面是对对象进行了冻结,不能修改不能删除,Object.freeze,原理是把属性的writable=false
标签:ret font div color ssi 代码 img turn i++
原文地址:https://www.cnblogs.com/lyt0207/p/12663742.html