javascript - 如何将输入值支持到 API 调用的参数中
问题描述
我有一个Header.js
接受用户输入并更新其状态的组件。我想将此项目传输(prop?)到父组件App.js
中,并将其作为参数放入其中,并且数据将相对于用户输入进行控制台记录。我不知道如何传递状态并将其实现到 API 的参数中。
class Header extends Component {
constructor() {
super();
this.state = {
query: '',
}
}
handleSubmit = (e) => {
e.preventDefault();
// form's input value
let userSearch = this.state.query;
}
handleChange = (e) => {
this.setState({
query: e.target.value
});
}
render() {
return (
<header>
<form onSubmit={this.handleSubmit}>
<input
onChange={this.handleChange}
type="text"
placeholder="Search"
/>
<label className="sr-only" htmlFor="search">Search News</label>
</form>
</header>
)
}
}
export default Header
import Header from './Components/Header'
import axios from 'axios';
class App extends Component {
constructor() {
super();
this.state = {
articles: [],
}
}
componentDidMount() {
axios({
// I want this.state.query in header.js to be {parameter}
url: 'http://newsapi.org/v2/everything?q={parameter}&sortBy=popularity&apiKey=where-the-key-goes',
method: 'GET',
responseType: 'JSON',
}).then((response => {
let articles = response.data.articles;
this.setState({
articles,
isLoading: false,
})
console.log(articles);
}))
}
render() {
return (
<>
<Header />
</>
)
}
}
export default App
解决方案
您可以在组件中创建一个回调函数并作为道具App
传递给:Header
class App extends Component {
...
handleSearch = (value) => {
axios({
url: `http://newsapi.org/v2/everything?q=${value}&sortBy=popularity&apiKey=where-the-key-goes`,
method: "GET",
responseType: "JSON",
}).then((response) => { ... });
};
render() {
return (
<>
<Header handleSearch={this.handleSearch} />
</>
);
}
}
然后在Header
'shandleSubmit
函数中使用它:
handleSubmit = (e) => {
e.preventDefault();
// form's input value
let userSearch = this.state.query;
this.props.handleSearch(userSearch);
};
推荐阅读
- python - ConnectionError: ('Connection aborted.', gaierror(-2, 'Name or service not known'))
- php - Wappalyzer如何检测网页的技术
- javascript - Jquery:形式的.blur()上的功能,而不是元素
- angular - 哪个 Angular 模块将 [computed]="var" 转换为 computed="hello"?
- android - 地理围栏服务
- html - 如何从本地 .css 文件中提取 html?
- c++ - 检索子菜单的 QMenu
- javascript - 使用 ajax (JQUERY) 发送文件
- php - Wordpress - Rev Slider 不替换短代码
- javascript - safari、edge 和 IE 上的 mouseenter 和 mouseleave