通过原生JS实现按钮+1/-1
http://js.jirengu.com/qapeb/1/edit?html,js,output
React实现
思路:只向页面传内容,不从页面获取内容
http://js.jirengu.com/zohububida/1/edit?html,css,js,output
React要导入React和React-DOM两个库
优化
let h = React.createElement
let number = 0
let onClickButton = () => {
number += 1
render()
}
let onClickButton2 = () => {
number -= 1
render()
}
render()
function render() {
ReactDOM.render(
h('div', {className: 'parent'},
h('span', {className: 'red'}, number),
h('button', {onClick: onClickButton}, '+1'),
h('button', {onClick: onClickButton2}, '-1')),
document.querySelector('#root'))
}
http://js.jirengu.com/tusal/1/edit?html,css,js,output
使用JSX
let number = 0
let onClickButton = () => {
number += 1
render()
}
let onClickButton2 = () => {
number -= 1
render()
}
render()
function render() {
ReactDOM.render(
// React.createElement('div', ...)
<div className='parent'>
<span className='red'>{number}</span>
<button onClick={onClickButton}>+1</button>
<button onClick={onClickButton2}>-1</button>
</div>,
document.querySelector('#root'))
}
http://js.jirengu.com/tusal/2/edit?html,css,js,output
JSX是JS的拓展,用写html的方式写JS
变量要写在{}里
虚拟节点是用对象表示的节点