如何使用将通过onClick()函数作为URL参数传递的参数创建函数?

时间:2019-04-08 14:26:11

标签: reactjs

我在创建具有参数的函数时遇到问题,参数值来自下拉列表,一旦用户单击按钮,该下拉列表将传递该值。该值将传递给componentDidMount以基于参数获取URL。互联网上有很多来源,但是我找不到一个将值从按钮传递到API调用的来源。因此,我在这方面需要帮助,因为我是第一次尝试这样做,希望我的问题能得到澄清。谢谢。

这是我的App.js代码

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
 constructor(){
     super();
     this.state={
        currencies: [],
        };



        }


handleChange =(event) => {

   let initialData = [];
        const url = `http://data.fixer.io/api/latest?access_key=ea263e28e82bbd478f20f7e2ef2b309f&symbols=${event.target.value}&format=1`

console.log("the url is: " + url)
 fetch(url).
  then(data =>{ return data.json();})
  .then(findData => {
   initialData = findData.rates
   console.log(initialData)
   this.setState({

        currencies: initialData,

        });
});

}

  render() {
    return (
      <div className="App">

    {this.state.currencies.map(o => <div> {o.rates}</div>)} //<---Newly //added line which cause an error saying this.state.currencies is not a function.


        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <p>
            Edit <code>src/App.js</code> and save to reload.
          </p>
     <h1 className="App-title"> Welcome to DKK website </h1>

        <div class="dropdown">
          <select id="select1" name ="currency" value={this.state.selectValue} onChange={this.handleChange}>
                <option value="EUR">-- Selecting: NILL --</option>
                <option value="CAD">-- Selecting: CAD --</option>
                <option value="SGD">-- Selecting: SGD --</option>
                <option value="AFN">-- Selecting: AFN --</option>
        </select>


        </div>


<button className="pressMe" > Set Button </button>
<br/>
<br/>


     <a
            className="App-link"
            href="https://reactjs.org"
            target="_blank"
            rel="noopener noreferrer"
          >
            Learn React
          </a>
        </header>
      </div>
    );
  }
}

export default App;

4 个答案:

答案 0 :(得分:0)

如果您刚刚输入

 <select 
        value={this.state.selectValue} 
        onChange={this.handleChange} 
      >

您可以从handleChange回调调用获取操作,例如

   handleChange = (event) => {
      let url = `http://data.fixer.io/api/latestaccess_key=ea263e28e82bbd478f20f7e2ef2b309f&symbols=${event.target.value}&format=1`
fetch(url)
.then....
    }

希望有帮助

答案 1 :(得分:0)

You can use onChange method in the select component.
For example..

<select onChange={this.handleSelect}>
  <option value='1'>Option 1</option>
</select>

function handleSelect (e) {
 // here you can access to the event properties
 this.setState({ selectedOption: e.target.value });
}

// EXAMPLE

import React, { Component } from 'react';

export default class MySelect extends Component {
  constructor (props) {
    super(props);
    this.state = {
      // Assuming the data is an array of object with one position -> array[0]
      initialData: [{data1: 1, data2: 2, data3: 3}],
      selectedOpt: ''
    };
  }

  handleOpt = event => {
    this.setState({ selectedOpt: event.target.value })
  }

  render () {
    const { initialData } = this.state;
    // One way is to use the keys
    const optKeys = Object.keys(initialData[0]);
    return (
      <div>
      <select onChange={this.handleOpt}>
        {
          optKeys.map((key, index) => {
            return (
              <option key={`opt-${index}`} value={initialData[0][key]}>
                {key}
              </option>
            );
          })
        }
      </select>
        <button onClick={() => console.log(this.state)}>CHECK STATE</button>
      </div>
    );
  }
}

答案 2 :(得分:0)

我看到两种方式。

1)将选择的输入电流值存储在状态(受控组件)中。您需要onChange供您选择。

var MySelect = React.createClass({
     getInitialState: function() {
         return {
             value: 'select'
         }
     },
     change: function(event){
         this.setState({value: event.target.value});
     },
     render: function(){
        return(
           <div>
               <select id="lang" onChange={this.change} value={this.state.value}>
                  <option value="select">Select</option>
                  <option value="Java">Java</option>
                  <option value="C++">C++</option>
               </select>
               <p></p>
               <p>{this.state.value}</p>
           </div>
        );
     }
});

React.render(<MySelect />, document.body);

然后可以在fetchData方法中将此值作为this.state.value。

2)在fetchData方法中从ref获取值:

this.item.value

P.S。您应该将按钮onClick事件处理程序附加如下:

onClick={this.fetchData}

答案 3 :(得分:0)

如果要在按钮上向函数添加参数,请单击以使用箭头功能:

onClick={() => this.fetchData(this.item.value)}  // to set parametr from ref
onClick={() => this.fetchData(this.state.value)} // to set parametr from state