SAPUI5 Select 渲染后列表中的第一项

SAPUI5 Select first item in list after rendering

我有一个主从应用程序,我希望在加载应用程序后自动选择第一个列表项。我尝试了以下解决方案,但它不起作用:

            onAfterRendering: function() {

              var oList = this.getView().byId("bankList");
              var aItems = oList.getItems("listItems");

              console.log(aItems);
                if (aItems.length) {
                    aItems[0].setSelected(true);
                 }
        }

奇怪的是 aItems 似乎是空的,尽管它包含正确的详细信息。下面是我 console.log(aItems):

时控制台打印的内容

console.log(aItems)

的结果

猜测您正在使用 sap.m.List,您应该使用 setSelectedItem() 函数,该函数接收 Item 对象作为参数。

此外,我建议您避免使用 onAfterRendering 生命周期方法,以保持生命周期清洁。通常有很多项目可以使用,例如 updateFinished for sap.m.List

这里是片段

<!DOCTYPE html>
<html>

<head>
  <meta http-equiv='X-UA-Compatible' content='IE=edge'>
  <meta charset="utf-8">

  <title>MVC with XmlView</title>

  <!-- Load UI5, select "blue crystal" theme and the "sap.m" control library -->
  <script id='sap-ui-bootstrap' src='https://sapui5.hana.ondemand.com/resources/sap-ui-core.js' data-sap-ui-theme='sap_belize_plus' data-sap-ui-libs='sap.m' data-sap-ui-xx-bindingSyntax='complex'></script>


  <!-- DEFINE RE-USE COMPONENTS - NORMALLY DONE IN SEPARATE FILES -->

  <!-- define a new (simple) View type as an XmlView
   - using data binding for the Button text
   - binding a controller method to the Button's "press" event
   - also mixing in some plain HTML
   note: typically this would be a standalone file -->

  <script id="view1" type="sapui5/xmlview">
    <mvc:View xmlns="sap.m" xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc" controllerName="my.own.controller">
      <List items="{/options}" mode="SingleSelect" updateFinished="onUpdateFinished">
        <StandardListItem title="{value}"></StandardListItem>
      </List>
    </mvc:View>
  </script>


  <script>
    // define a new (simple) Controller type
    sap.ui.controller("my.own.controller", {
      onUpdateFinished: function(oEvent) {
        var oList = oEvent.getSource();
        var aItems = oList.getItems();
        oList.setSelectedItem(aItems[0])
      }
    });



    /*** THIS IS THE "APPLICATION" CODE ***/
    // create some dummy JSON data
    var data = {
      options: [{
        key: '1',
        value: 'option 1'
      }, {
        key: '2',
        value: 'option 2'
      }, {
        key: '3',
        value: 'option 3'
      }]
    };
    var oJSONModel = new sap.ui.model.json.JSONModel();
    oJSONModel.setData(data);

    // instantiate the View
    var myView = sap.ui.xmlview({
      viewContent: jQuery('#view1').html()
    }); // accessing the HTML inside the script tag above

    myView.setModel(oJSONModel);
    // put the View onto the screen
    myView.placeAt('content');
  </script>

</head>

<body id='content' class='sapUiBody'>
</body>

</html>