我比较了VanJS和React的代码编写方式
VanJS的编码方式可以像React的编码方式一样写。对于那些有编写过React代码但尚未尝试VanJS,或者正在考虑学习成本等问题的人来说,这可能会提供一些参考。
這段程式碼進行比較
我使用VanJS和React创建了一个完全相同的计数器应用程序。我将使用这个应用程序来比较VanJS和React的代码编写方式。
VanJS的代码
const { div, h1, img, p, button } = van.tags
const Button = ({ increment }) => {
return div(
button(
{
type: 'button',
onclick: () => increment(),
},
'Increment',
)
)
}
const Counter = () => {
const count = van.state(0)
const increment = () => {
count.val++
}
return div(
h1('Counter'),
img({ src: 'src/image.jpg', alt: 'image', class: 'image' }),
p('Count: ', count),
Button({ increment }),
)
}
van.add(document.getElementById('app'), Counter())
React的代码
import { useState } from 'react'
const Button = ({ increment }) => {
return (
<div>
<button
type="button"
onClick={() => increment()}
>
Increment
</button>
</div>
)
}
const Counter = () => {
const [count, setCount] = useState(0)
const increment = () => {
setCount(count + 1)
}
return (
<div>
<h1>Counter</h1>
<img src="src/image.jpg" alt="image" className="image" />
<p>Count: {count}</p>
<Button increment={increment} />
</div>
)
}
export default Counter
应用程序参考图片

尝试对比一下
标签
VanJS需要声明变量。将文本用引号(可以是双引号或模板字面量)括起来,并将其作为参数传递。
const { div, h1, img, p, button } = van.tags
h1('Counter')
<h1>Counter</h1>
特性
VanJS使用对象来定义属性,使用class关键字来定义类。
img({ src: 'src/image.jpg', alt: 'image', class: 'image' })
<img src="src/image.jpg" alt="image" className="image" />
点击事件 jī shì
在VanJS中,可以使用onclick: () => {}调用点击事件。
button(
{
type: 'button',
onclick: () => increment(),
},
'Increment',
)
<button
type="button"
onClick={() => increment()}
>
Increment
</button>
状态管理
在VanJS中,您可以使用van.state来创建状态管理的变量。通过更改van.val的值来修改变量的值。在示例中,我们使用count.val++来改变值,但您也可以使用以下的写法。
-
- count.val += 1
-
- count.val = count.val + 1
- ++count.val
const count = van.state(0)
const increment = () => {
count.val++
}
const [count, setCount] = useState(0)
const increment = () => {
setCount(count + 1)
}
组件
VanJS和React的组件编写方式相似。组件调用时,props参数以对象的形式书写,类似于属性。在示例中,由于键名和变量名都是increment,因此可以使用省略记法来书写。
const Button = ({ increment }) => {
return div(
// 省略
)
}
// 呼び出し
Button({ increment })
const Button = ({ increment }) => {
return (
<div>
{/* 省略 */}
</div>
)
}
// 呼び出し
<Button increment={increment} />
总结
我在一个计数器应用中比较了VanJS和React的代码编写方式。如果您熟悉React,那么您将很容易理解。学习成本也不高,所以如果您感兴趣,请务必尝试一下VanJS。
最后
在GoQSystem,我们正在招募愿意与我们一起共事的伙伴!
如果您有兴趣,请通过以下链接确认。