React - 动态地为autosuggest添加值

时间:2018-03-19 18:23:15

标签: reactjs

我的表单中有输入positiononKeyUp脚本发送

handlePositionKeyUp(e) {

        axios({
            method: 'GET',
            url: 'https://example.com/suggests/positions/?text='+e.target.value, 
            headers: { 
                'User-Agent': 'React App/1.0 (myemail@gmail.com)',
                '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并为此输入动态创建自动提示?

1 个答案:

答案 0 :(得分: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 (myemail@gmail.com)', 
                'HH-User-Agent': 'React App/1.0 (myemail@gmail.com)',  
                '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);
          });
    } 
}

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