在反应中将表格输入值传递给方法

时间:2019-07-23 14:54:30

标签: javascript reactjs

我正在为需要调用输入字段的值进行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,但这也不起作用。知道如何解决这个问题吗?

2 个答案:

答案 0 :(得分:2)

您正在使用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>
        );
    }
}

更好的方法是使用state。这称为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>
        );
    }
}

答案 1 :(得分:1)

您可以使用受控组件:https://reactjs.org/docs/forms.html

我在代码段中模拟了提取操作。

active_users
const fetchWeather = function (data) {
  // simulating fetch
  setTimeout(function() {
    console.log('GETTING DATA ' + JSON.stringify(data))
  }, 500)
}

// Controlled Component: https://reactjs.org/docs/forms.html
class App extends React.PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      city: ''
    }

    this._handleInputChange = this._handleInputChange.bind(this)
    this._handleSubmit = this._handleSubmit.bind(this)
  }

  _handleInputChange (event) {
    const { value, name } = event.target

    this.setState({
      [name]: value
    })
  }
  
  _handleSubmit (event) {
    event.preventDefault()
    fetchWeather(this.state)
  }

  render() {
    const { city } = this.state
    
    return (
      <div>
        <form onSubmit={this._handleSubmit}>
          <input
            type='text'
            name='city'
            placeholder='Your city'
            value={city}
            onChange={this._handleInputChange}
          />
          <input type='submit' placeholder='Submit' value='Submit' />
        </form>
      </div>
    )
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('react')
)