【问题标题】:can attributes of web components be functions?Web组件的属性可以是函数吗?
【发布时间】:2017-03-11 23:36:36
【问题描述】:

React 非常强大的特性之一是能够将函数作为道具传递:

<Counter getText={count => `Count: ${count}`} />

Counterrender方法中,它可以用count调用这个函数:

render() {
  const {getText} = this.props
  const {count} = this.state
  return <div className="counter">{getText(count)}</div>
}

当然,HTML 有用于事件处理函数的语法...

<p id="demo" onclick="myFunction()">Click me to change my text color.</p>

调用函数的参数是硬编码的。我想知道是否可以为 Web 组件赋予一个函数属性,它可以使用它想要的任何参数调用它?

【问题讨论】:

    标签: dom polymer web-component


    【解决方案1】:

    是的,你可以。

    onclick="myFunction()" 
    

    应该是

    onclick="myFunction.bind(this,arguementsGoHere)"
    

    【讨论】:

    • 好的,你能举一个从 Web 组件调用 myFunction 的例子吗?
    • argumentsGoHere 你的意思是参数必须在那个字符串中吗?因为我问是否有办法稍后传递参数,而不是将它们写在onclick 字符串中。
    • 这就是你要找的东西:&lt;p id="demo" onclick={this.changeColor.bind(this,this.state.color)}&gt;Click me to change my text color.&lt;/p&gt;
    • 也许把你所有的代码放在上下文中——比如一个文件,并有你尝试过的代码,所以我们可以看到我们需要修复什么?
    • 我实际上并没有做任何编程,我只是出于好奇而询问 Web 组件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-03
    • 1970-01-01
    • 2023-01-17
    • 2014-04-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多