ExtJS有条件地呈现输入字段

ExtJS conditionally render input fields

本文关键字:输入 字段 有条件 ExtJS      更新时间:2023-09-26

ExtJS 中有以下代码

var formPanel = Ext.create('Ext.form.Panel', {
title: 'Panel title',
renderTo: Ext.getBody(),
items: [{
    xtype: 'container',
    layout: 'hbox',
    items: [{
        xtype: 'textfield',
        fieldLabel: 'First Name', 
        name: 'FirstName',
    }, {
        xtype: 'textfield',
        fieldLabel: 'Last Name',  
        name: 'LastName',
    },{
        xtype:'fieldset',
        title: 'Phone Number',
        defaultType: 'textfield',
        items :[{
                fieldLabel: 'Home',
                name: 'home',
                value: '(888) 555-1212'
            },{
                fieldLabel: 'Business',
                name: 'business',
                toBeRendered: IS_BUSINESS_FIELD_SUPPORTED_IN_CURRENT_RELEASE // custom property that must restrict rendering
                rendered: IS_BUSINESS_FIELD_SUPPORTED_IN_CURRENT_RELEASE //doesn't work
            }]
    }]
}]
});

我想创建一个应用程序,它将具有属性文件,我可以在其中设置SUPPORTED字段的标志,例如IS_BUSINESS_FIELD_SUPPORTED_IN_CURRENT_RELEASE = false。如果为false,则根本不会呈现文本输入fieldLabel: 'Business'——在html中没有隐藏/禁用的文本输入Business

我尝试过rendered属性,但它不起作用,到目前为止唯一的解决方案是在onRender中使用items = Ext.Array.filter(items,filterFunction)

有其他解决方案吗?如何限制渲染输入元素?

提前谢谢。

使用initItems方法代替构造函数:

Ext.define('MyComponent', {
    extend: 'Ext.panel.Panel',
    xtype: 'mycomponent',
    bodyPadding: 10,
    border: true,
    title: 'My component',
    items : [
        {
            xtype: 'button',
            text: 'My allowed button'
        }
    ],
    initItems : function() {
        var items = this.items;
        // Your conditions
        if (false) {
            items.push({
                xtype: 'button',
                text: 'My denied button'
            });
        }
        this.callParent();
    }
});

https://fiddle.sencha.com/#fiddle/17qi

我认为最好的方法是为您的应用程序部件定义自定义组件,并在其constructor中添加所需组件,如下所示:

constructor: function () {
    var myComponentItems = [
    {
        xtype: 'button',
        text: 'My allowed button'
        }
    ];
    // Your conditions
    if(false) {
        myComponentItems.push({
            xtype: 'button',
            text: 'My denied button'
        });
    }
    Ext.apply(this, {
        items: myComponentItems
    });
    this.callParent(arguments);
}

工作小提琴