首页 > 解决方案 > 使用数据绑定文本淘汰自定义组件

问题描述

我有一个自定义组件,我们称之为它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: ...'

标签: javascriptknockout.js

解决方案


“文本”绑定仅在与本机 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>'
});

推荐阅读