首页 > 解决方案 > 如何将输入值支持到 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

标签: javascriptreactjsstatereact-props

解决方案


您可以在组件中创建一个回调函数并作为道具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);
};

推荐阅读