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);
});
};
因此,大家可以看到我要傳遞的輸入值到一個變量稱爲搜索關鍵詞。
要完全誠實,我不明白你的意思。當我嘗試這個時,我收到一條錯誤消息,說該值未定義。 – Naomi
@Naomi我已經更新了我的答案,包括一個工作示例。 –
雖然這並不回答我的問題。它不會將該變量傳遞給AJAX請求。 – Naomi