简体   繁体   English

带有数据绑定文本的敲除自定义组件

[英]Knockout custom component with data-bind text

I have a custom component, let's call it mycomp , that accesses text it's passed in its template like this:我有一个自定义组件,我们称之为mycomp ,它访问它在其模板中传递的文本,如下所示:

<p>
    <!-- ko template: { nodes: $componentTemplateNodes } --><!-- /ko -->
</p>

I use this component in another component and try to pass a text to it like this:我在另一个组件中使用这个组件并尝试像这样向它传递文本:

<mycomp data-bind='text: myProperty'></mycomp>

When I try to run this, I get当我尝试运行它时,我得到

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.

Is there a way to fix the issue and do what I want to do, namely use a component in another component and pass it text via data-bind='text: ...' ?有没有办法解决这个问题并做我想做的事情,即在另一个组件中使用一个组件并通过data-bind='text: ...'传递文本?

"text" binding only makes sense when used with native dom elements (div, span, etc) or virtual elements as it's changes all the element content with the specified text. “文本”绑定仅在与原生 dom 元素(div、span 等)或虚拟元素一起使用时才有意义,因为它会使用指定的文本更改所有元素内容。

This is what the error message is saying (both, "text binding" and the component itself are trying to change the content).这就是错误消息所说的(“文本绑定”和组件本身都在尝试更改内容)。

Your component seems to output all the template nodes, so I think it will work if you do this:你的组件似乎输出了所有的模板节点,所以我认为如果你这样做的话它会起作用:

<mycomp>hello</mycomp>

After your update, I think you have 2 options:更新后,我认为您有两个选择:

<mycomp>
    <!-- ko text: myProperty --><!-- /ko -->
</mycomp>

Or create custom parameter for your component, so you can do this:或者为您的组件创建自定义参数,以便您可以执行以下操作:

<mycomp params="text: myProperty"></mycomp>

Details on how to to this are here => https://knockoutjs.com/documentation/component-overview.html关于如何做到这一点的详细信息在这里=> https://knockoutjs.com/documentation/component-overview.html

In your case, I think it would be like this:在你的情况下,我认为它会是这样的:

ko.components.register('mycomp', {
    viewModel: function(params) {
        this.text= params.text;
    },
    template:
        '<p data-bind="text: text"></p>'
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM