我正在努力解决需要获取输入字段的值以进行 API 调用的情况。
所以我所拥有的是:
import React, { Component } from 'react'
import axios from 'axios';
const fetchWeather = function (e) {
e.preventDefault();
axios.get('https://api.openweathermap.org/data/2.5/weather?q=Zeist&appid=MYID')
.then(res => {
console.log(res.data);
});
console.log();
}
export default class App extends Component {
render() {
return (
<div>
<form onSubmit = {fetchWeather}>
<input type = 'text' placeholder = 'Your city' ref="city"></input>
<input type = 'submit' placeholder='Submit' value = 'Submit'></input>
</form>
</div>
);
}
}
在提交时运行函数的表单,我使用 preventDefault
来阻止页面加载。
该函数运行并且页面不会重新加载。现在我想从输入字段中获取文本并将其记录在该函数中。我想要这个的原因是我可以在 API 调用中将它用作查询参数。我尝试了很多事情。我尝试记录e
来看看里面有什么。这是一个非常大的对象,我找不到我正在寻找的值。我尝试使用ref
,这也不起作用。知道如何解决这个问题吗?
最佳答案
您正在使用Uncontrolled Components .
您需要将 fetchWeather
函数移至组件内部,
export default class App extends Component {
fetchWeather = (e) => {
e.preventDefault();
console.log(this.refs.city.value)//You will get vlue here
axios.get('https://api.openweathermap.org/data/2.5/weather?q=Zeist&appid=MYID')
.then(res => {
console.log(res.data);
});
console.log();
}
render() {
return (
<div>
<form onSubmit = {this.fetchWeather}> //refer your function using `this`
<input type = 'text' placeholder = 'Your city' ref="city"></input>
<input type = 'submit' placeholder='Submit' value = 'Submit'></input>
</form>
</div>
);
}
}
<小时/>
更好的方法是使用状态
。这称为Controlled Components .
export default class App extends Component {
state={
city: ''
}
handleChange = (e) => {
this.setState({[e.target.name]:e.target.value})
}
fetchWeather = (e) => {
e.preventDefault();
console.log(this.state.city)//You will get vlue here
axios.get('https://api.openweathermap.org/data/2.5/weather?q=Zeist&appid=MYID')
.then(res => {
console.log(res.data);
});
console.log();
}
render() {
return (
<div>
<form onSubmit = {this.fetchWeather}> //refer your function using `this`
<input type = 'text' placeholder = 'Your city' name="city" value={this.state.city} onChange={this.handleChange} ></input>
<input type = 'submit' placeholder='Submit' value = 'Submit'></input>
</form>
</div>
);
}
}
关于javascript - 将表单输入值传递给 react 中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57166925/