gpt4 book ai didi

javascript - 将输入值传递给 React 中的 AJAX 请求

转载 作者:太空宇宙 更新时间:2023-11-04 15:57:51 25 4
gpt4 key购买 nike

我正在使用 Github Search API,以便人们能够在 github 上搜索存储库。我正在使用 React,并且对这一切都很陌生。我想将输入值传递给 AJAX 请求,以便它只请求具有特定名称的存储库。有没有办法使用React来传递输入值?

 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);
});
};

正如您所看到的,我想将输入值传递到一个名为 searchTerm 的变量中。

最佳答案

您可以添加ref属性到您想要引用的 DOM 元素。然后你可以在你的 react 组件中引用该元素。

根据您的情况,您可以将 ref 添加到搜索框,如下所示

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

然后在你的 React 组件中将其值引用为 this.searchBox.value

请记住,如果您使用 react 状态来管理应用程序的状态,则需要将获取请求放入组件中。如果您不想这样做,我建议您查看 FluxRedux用于您的应用程序的状态管理。

编辑

根据您的评论,我创建了一个 codepen 来说明如何使用 ref 属性引用输入字段的值 http://codepen.io/DeividasK/pen/PpZpNL .

关于javascript - 将输入值传递给 React 中的 AJAX 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42536375/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com