2017-03-01 64 views
1

我正在使用Github Search API来让人们能够在github上搜索存储库。我正在使用React,并且对于所有这些都很新颖。 我想将输入值传递给AJAX请求,因此它只会请求具有特定名称的存储库。有没有使用React来传递输入值的方法?将输入值传递给React中的AJAX请求

class SearchBox extends React.Component { 

constructor(props) { 
    super(props); 
    this.onKeyUp = this.onKeyUp.bind(this); 
    this.onChange = this.onChange.bind(this); 
} 



render() { 
    return(
     <form> 
      <input type="text" className="searchbox" onChange={this.onChange} onKeyUp={this.onKeyUp} /> 
       <ul className="suggestions"> 
     <li>Filter for a city</li> 
     <li>or a state</li> 
    </ul> 
     </form> 
    ); 
} 

    onChange(event) { 
     const matchArray = findMatches(this.value, repositories); 
const html = matchArray.map(place => { 
    const regex = new RegExp(this.value, "gi"); 
    const cityName = place.city.replace(regex, `<span className="hl">${this.value}</span>`); 
    const stateName = place.state.replace(regex, `<span className="hl">${this.value}</span>`); 
    return ` 
    <li> 
    <span className="name">${cityName}, ${stateName}</span> 

    </li> 
    `; 
}).join(''); 
console.log(matchArray); 


} 

onKeyUp(event) { 
     const matchArray = findMatches(this.value, repositories); 
const html = matchArray.map(place => { 
    const regex = new RegExp(this.value, "gi"); 
    const cityName = place.name.replace(regex, `<span className="hl">${this.value}</span>`); 

    return ` 
    <li> 
    <span class="nameName">${cityName}, </span> 

    </li> 
    `; 
}).join(''); 
console.log(matchArray); 


} 
} 

ReactDOM.render(
<SearchBox />, 
document.getElementById("searching") 
); 

JS

const endpoint = 'https://api.github.com/search/repositories?sort=stars&order=desc&q=' + searchTerm; 
const repositories = []; 

fetch(endpoint) 
.then(blob => blob.json()) 
.then(data => repositories.push(...data)); 

function findMatches(wordToMatch, repositories) { 
return repositories.filter(place => { 

    const regex = new RegExp(wordToMatch, "gi"); 
    return place.city.match(regex) || place.state.match(regex); 
}); 
}; 

因此,大家可以看到我要传递的输入值到一个变量称为搜索关键词。

回答

1

您可以添加ref属性,你想获得参考的DOM元素。然后你可以在你的反应组件中引用该元素。

在你的情况,你可以添加ref搜索框如下

<input type="text" ref={(input) => { this.searchBox = input; }} className="searchbox" ... /> 

,然后参考它的价值在你的反应组件作为this.searchBox.value

贝阿记住,如果你正在使用的反应状态来管理你的应用程序的状态,你需要把你的获取请求的组件。如果你不想这样做,我建议你看看FluxRedux为你的应用程序的状态管理。

编辑

基于您的评论我创建了一个codepen解说了一种如何能指的是输入字段的值使用ref属性http://codepen.io/DeividasK/pen/PpZpNL

+0

要完全诚实,我不明白你的意思。当我尝试这个时,我收到一条错误消息,说该值未定义。 – Naomi

+0

@Naomi我已经更新了我的答案,包括一个工作示例。 –

+0

虽然这并不回答我的问题。它不会将该变量传递给AJAX请求。 – Naomi