React in 33 lines

栏目: IT技术 · 发布时间: 5年前

内容简介:It also does a load of other crap as well, but we're going to ignore that.In this post, I'm going to make the smallest React-like thing that can do the above. It's very

33 line React

React

  • you pass in a function that takes state and returns a virtual DOM (just a tree of plain ol' js objects)
  • it renders that virtual DOM as a real DOM in the browser
  • if you change the state, it runs the function again, this returns a new virtual DOM
  • it efficiently updates the real DOM so that it matches the new virtual DOM

It also does a load of other crap as well, but we're going to ignore that.

In this post, I'm going to make the smallest React-like thing that can do the above. It's very mithril influenced.

Here is a sample calendar picker application that uses the library .

Lots of the code looks pretty code-golfy - I promise I don't do stuff like this at work, neither should you :-)

Noughts and crosses

We're going to make this noughts and crosses game:

Now let's look at the code to this, you can also just view the page source if you want.

let currentPlayer = 'o'
let winner = null
const g = [['', '', ''], ['', '', ''], ['', '', '']]  // grid

const move = (value, i, j)=>{
    // ... game logic goes here
    renderNoughts()
}

const Cell = (value, i, j)=>m('button.cell',
    {onclick: ()=>move(value, i, j)}, value
)
const Noughts = ()=>m('',
    winner
        ? m('marquee', `winner: ${winner}`)
        : m('h3', `current player: ${currentPlayer}`),
    m('table', g.map(
        (row, i)=>m('tr', row.map(
            (value, j)=>m('td', {class: value}, Cell(value, i, j)))))),
)

const renderNoughts = ()=>m.render(
    document.getElementById('noughts'),
    {children: [Noughts()]},
)
renderNoughts()

Cute, so what's going on?

First we defined some state:

let currentPlayer = 'o'
let winner = null
const g = [['', '', ''], ['', '', ''], ['', '', '']]  // grid

These hold the state of our game, we will mutate them.

const move = (value, i, j){...}

This function makes a move in the game, it takes 'x' or 'o' along with 2 integer coordinates. It will mutate all the state variables to reflect the new state of the game. After that, it calls renderNoughts() , this is a call to rerender the game - but we'll come back to that.

Next we define the functions that return virtual DOMs, Noughts and Cell .

The m(...) calls take:

  • a tag name (eg. 'tr' ), with . -separated class names
  • (optionally) a {string: any} object containing all the attributes to attach to the DOM node
  • an arbitrarily nested list of children - these are other virtual DOM nodes or strings of text
And return virtual DOM elements, for example, calling Noughts()

would return:

{
    tag: 'div',
    attrs: {},
    classes: [],
    children: [
        {
            tag: 'h3',
            attrs: {},
            classes: [],
            children: [
                'current player: x'
            ]
        },
        {
            tag: 'table',
            attrs: {},
            classes: [],
            children: [
                {
                    tag: 'tr',
                    attrs: {},
                    classes: [],
                    children: [
...

Next we make the function renderNoughts() , when you call it, it will call our Noughts function, and attempt to efficiently render the resulting virtual DOM onto document.getElementById('noughts')

How does m work?

Here's the source with and without comments.


以上所述就是小编给大家介绍的《React in 33 lines》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

程序员成长的烦恼

程序员成长的烦恼

吴亮、周金桥、李春雷、周礼 / 华中科技大学出版社 / 2011-4 / 28.00元

还在犹豫该不该转行学编程?还在编程的道路上摸爬滚打?在追寻梦想的道路上你并不孤单,《程序员成长的烦恼》中的四位“草根”程序员也曾有过类似的困惑。看看油田焊接技术员出身的周金桥是如何成功转行当上程序员的,做过钳工、当过外贸跟单员的李春雷是如何自学编程的,打小在486计算机上学习编程的吴亮是如何一路坚持下来的,工作中屡屡受挫、频繁跳槽的周礼是如何找到出路的。 《程序员成长的烦恼》记录了他们一步一......一起来看看 《程序员成长的烦恼》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

URL 编码/解码
URL 编码/解码

URL 编码/解码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具