Build up some UI with mithril.js and jsx

问题: I'm new to javascript and its ecosystem. I'm trying to build some components using mithril.js. My goal is to have a component that shows some properties and provides a coup...

问题:

I'm new to javascript and its ecosystem. I'm trying to build some components using mithril.js. My goal is to have a component that shows some properties and provides a couple of button for each of them. Just to learn about mithril.js and jsx. Here is what I did so far:

const m = require("mithril");
var Something = {
  _increase: function(category) {
    console.log("increase category: "+category);
  },
  _decrease: function(category) {
    console.log("decrease category: "+category);
  },
  view: function(vnode) {
    return <div> 
      {Object.keys(vnode.attrs.categories).map((category)=> {
        return <div>
          <label for={category}>{category}</label>
          <input type="number" id={category} value={vnode.attrs.categories[category]} />
          <button type="button" onclick="{this._increase(category)}">MORE</button>
          <button type="button" onclick="{this._decrease(category)}">LESS</button>
        </div>
      })}
    </div>
  }
}
export default Something;

Well, component seems to work fine, node doesn't complain and labels and buttons and fields are displayed on page, but, when I click on a button, nothing happen. It looks like event isn't fired. What's wrong?


回答1:

Two things: (1) I think you should just put the function into the onclick handler braces instead of encoding the function in a string. (2) It looks like you're immediately invoking the function, not declaring that the onclick handler is a function that uses the category argument. Try passing in an anonymous function with no arguments, that way you when the onclick event is fired it can take in the category as a parameter:

onclick={() => this._increase(category)}
onclick={() => this._decrease(category)}    
  • 发表于 2019-01-01 01:04
  • 阅读 ( 227 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除