React - 动态地为autosuggest添加值

问题描述 投票:0回答:1

在我的表格中输入positiononKeyUp脚本发送

handlePositionKeyUp(e) {

        axios({
            method: 'GET',
            url: 'https://example.com/suggests/positions/?text='+e.target.value, 
            headers: { 
                'User-Agent': 'React App/1.0 ([email protected])',
                'Content-Type':'application/x-www-form-urlencoded',
            }
            })
          .then(function (response) {
            console.log(response);
          })
          .catch(function (error) {
            console.log(error);
          });
    }

response包含datadata包含阵列items,每个items都有name。是否有可能从names获取所有response并为此输入动态创建自动提示?

reactjs
1个回答
0
投票

我的解决方案

handlePositionKeyUp(e) {
    if(e.target.value.length > 1) {

        axios({
            method: 'GET',
            url: 'https://example.com/suggests/positions/?text='+e.target.value, 
            headers: { 
                'User-Agent': 'React App/1.0 ([email protected])', 
                'HH-User-Agent': 'React App/1.0 ([email protected])',  
                'Content-Type':'application/x-www-form-urlencoded',
            }
            })
          .then(function (response) {
            var positionsList = document.createElement('datalist');
            positionsList.setAttribute("id","positions-list");

            var positionsListInner = "";
            for (var i = 0; i < response.data.items.length; i++) {
               positionsListInner += "<option value='"+ response.data.items[i].text +"'>";    
            }

            positionsList.innerHTML = positionsListInner;

            var el = document.getElementById("positions-list");
            if (el) {
                el.parentNode.removeChild(el);
            }

            var posWrap = document.getElementById('position-wrap');
            posWrap.appendChild(positionsList);

          })
          .catch(function (error) {
            console.log(error);
          });
    } 
}

它不是很漂亮,有点工作。

© www.soinside.com 2019 - 2024. All rights reserved.