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