javascript - 使用数据绑定文本淘汰自定义组件
问题描述
我有一个自定义组件,我们称之为它mycomp
,它访问它在其模板中传递的文本,如下所示:
<p>
<!-- ko template: { nodes: $componentTemplateNodes } --><!-- /ko -->
</p>
我在另一个组件中使用这个组件并尝试像这样向它传递一个文本:
<mycomp data-bind='text: myProperty'></mycomp>
当我尝试运行它时,我得到
Unable to process binding "component: function(){return l}"
Message: Multiple bindings (text and component) are trying to control descendant bindings of the same element. You cannot use these bindings together on the same element.
有没有办法解决这个问题并做我想做的事,即在另一个组件中使用一个组件并通过它传递文本data-bind='text: ...'
?
解决方案
“文本”绑定仅在与本机 dom 元素(div、span 等)或虚拟元素一起使用时才有意义,因为它会使用指定的文本更改所有元素内容。
这就是错误消息的含义(“文本绑定”和组件本身都在尝试更改内容)。
您的组件似乎输出了所有模板节点,所以我认为如果您这样做,它将起作用:
<mycomp>hello</mycomp>
更新后,我认为您有两个选择:
<mycomp>
<!-- ko text: myProperty --><!-- /ko -->
</mycomp>
或者为您的组件创建自定义参数,因此您可以这样做:
<mycomp params="text: myProperty"></mycomp>
关于如何做到这一点的详细信息在这里=> https://knockoutjs.com/documentation/component-overview.html
在你的情况下,我认为它会是这样的:
ko.components.register('mycomp', {
viewModel: function(params) {
this.text= params.text;
},
template:
'<p data-bind="text: text"></p>'
});
推荐阅读
- gauge - 具有多种带颜色的icCube量规
- python - 如何在 python 中输入“n”来定义 n 阶矩阵?
- django - 由于夹具错误,Django datadump 和 loaddata 无法正常工作
- algorithm - D* lite:如何比较和排序配对的键?
- stripe-payments - 处理条带支付网关客户延迟的正确方法
- java - Android studio:无法检测到adb版本,退出值0xc0000135
- apache-spark - delta Lake 是否支持加入更新?
- node.js - Base64 到 Pdf 导出问题 AWS Lambda
- amazon-web-services - 如何将自签名证书分配给 AWS elastick beanstalk 应用程序
- python - 如何优雅地处理 for 循环中的多个 continue 语句