我下面是通过扩展sap.m.Input创建的自定义控件,该输入仅允许用户输入数字。但是,当实际存在错误时,控件的状态将变为带有红色边框的“错误”,但是valueStateText具有焦点时不会显示。如何获取自定义控件的valueStateText?它不应该从sap.m.Input继承吗?
自定义控制代码:
sap.ui.define([
"sap/m/Input"
], function (Control) {
"use strict";
return Control.extend("sample.control.NumericInput", {
metadata: {
properties: {},
aggregations: {},
events: {}
},
init: function () {
if (sap.ui.core.Control.prototype.onInit) {
sap.ui.core.Control.prototype.onInit.apply(this, arguments);
}
this.attachLiveChange(this.onLiveChange);
},
renderer: function (oRM, oControl) {
sap.m.InputRenderer.render(oRM, oControl);
},
onLiveChange: function (e) {
var _oInput = e.getSource();
var val = _oInput.getValue();
val = val.replace(/[^\d]/g, "");
_oInput.setValue(val);
}
});
});
XML代码:
<hd:NumericInput value="{path:'payload>/MyNumber',type:'sap.ui.model.type.String',constraints:{minLength:1,maxLength:10}}" valueStateText="My Number must not be empty. Maximum 10 characters."/>
在init
覆盖中,您需要调用父控件的init
(而不是sap.ui.core.Control
的onInit)。 init
(sap.m.InputBase
的父类)的sap.m.Input
设置了valuestate的初始值和渲染,因此它丢失了所有代码,并且无法正常工作。
根据您的代码查看此示例:
sap.ui.define([
"sap/m/Input"
], function (Control) {
"use strict";
return Control.extend("sample.control.NumericInput", {
metadata: {
properties: {},
aggregations: {},
events: {}
},
init: function () {
Control.prototype.init.apply(this, arguments);
this.attachLiveChange(this.onLiveChange);
},
renderer: function (oRM, oControl) {
sap.m.InputRenderer.render(oRM, oControl);
},
onLiveChange: function (e) {
var _oInput = e.getSource();
var val = _oInput.getValue();
val = val.replace(/[^\d]/g, "");
_oInput.setValue(val);
}
});
});
// Small model
const model = new sap.ui.model.json.JSONModel({
MyNumber: "10000000000000000000",
});
// Create an example of the control (JS not XML but idea is the same)
const input = new sample.control.NumericInput({
valueState: "Error",
valueStateText:"My Number must not be empty. Maximum 10 characters.",
value: {
path:'/MyNumber',
type:'sap.ui.model.type.String',
constraints:{minLength:1,maxLength:10}
}
});
input.setModel(model);
input.placeAt('content');
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<script
src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js"
id="sap-ui-bootstrap"
data-sap-ui-theme="sap_fiori_3"
data-sap-ui-xx-bindingSyntax="complex"
data-sap-ui-libs="sap.m"></script>
</head>
<body class="sapUiBody sapUiSizeCompact">
<div id='content'></div>
</body>
</html>