2017-03-01 38 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