如何区分哪个组件称为回调函数?

时间:2018-03-29 20:54:38

标签: javascript reactjs

我很反应,抱歉,如果这是新问题。我有一个组件Dropdown,它通过回调函数返回一个值。我想渲染两次以选择两个不同的值,然后简单地渲染下面的选定值。如何允许两个不同的组件向组件发送不同的数据。以下是我的代码。

index.js

import { Dropdown } from './components/dropdown'

class App extends Component {
  constructor(props) {
    super(props);
    this.calculateRate = this.calculateRate.bind(this);
    this.callApi = this.callApi.bind(this);
    this.state = {
      response: "",
      currA: 0,
      currB: 1
    }
  }

  componentDidMount() {

    this.callApi()
      .then(res => this.setState({ response: res.express }))
      .catch(err => {console.log(err)});

  }

  callApi = async () => {
    const response = await fetch('/main');
    const body = await response.json();
    if (response.status !== 200) throw Error(body.message);
    return body;
  }

  calculateRate = (key, val) => {
    // if the calling agent sent currA data, update currA,
    // else if the calling agent sent currB data, update currB
    if (key === 'A') this.setState({currA: val})
    if (key === 'B') this.setState({currB: val})
    console.log('updated curr' + key + ' to ' + val);
  }

  render() {
    return (
      <div className='App'>
        <div>
          <Dropdown callbackFromParent={this.calculateRate}
            stateKey={'A'} val={this.state.currA} />
          <Dropdown callbackFromParent={this.calculateRate}
            stateKey={'B'} val={this.state.currB} />
        </div>
      </div>
    );
  }
}


export default App;

dropdown.js

export class Dropdown extends React.Component {

  constructor(props){
    super(props);
    this.state = {
      list: [],
      selected: ""
    };
  }

componentDidMount(){
  fetch('https://api.fixer.io/latest')
    .then(response => response.json())
    .then(myJson => {
      this.setState({ list: Object.keys(myJson.rates) });
    });
}

  render(){
    var selectCurr = (curr) =>
     <select
      onChange={event => props.callbackFromParent(props.stateKey, event.target.value)}
     >
     {(this.state.list).map(x => <option>{x}</option>)}
     </select>;

    return (
      <div>
        {selectCurr()}
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:1)

我不确定您要尝试实现的目标,但希望以下内容说明如何允许您的两个不同组件向<App>组件发送不同的数据。

重要的变化是:我们需要将方法绑定到<App>函数中的constructor()组件,然后我们可以使用.bind()组件中的Dropdown方法来指定要传递给回调函数的数据:

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

class App extends Component {
  constructor(props) {
    super(props);
    this.calculateRate = this.calculateRate.bind(this);
    this.callApi = this.callApi.bind(this);
    this.state = {
      response: "",
      currA: 0,
      currB: 1
    }
  }

  componentDidMount() {
    /*
    this.callApi()
      .then(res => this.setState({ response: res.express }))
      .catch(err => {console.log(err)});
    */
  }

  callApi = async () => {
    const response = await fetch('/main');
    const body = await response.json();
    if (response.status !== 200) throw Error(body.message);
    return body;
  }

  calculateRate = (key, val) => {
    // if the calling agent sent currA data, update currA,
    // else if the calling agent sent currB data, update currB
    if (key === 'A') this.setState({currA: val})
    if (key === 'B') this.setState({currB: val})
    console.log('updated curr' + key + ' to ' + val);
  }

  render() {
    return (
      <div className='App'>
        <div>
          <Dropdown callbackFromParent={this.calculateRate}
            stateKey={'A'} val={this.state.currA} />
          <Dropdown callbackFromParent={this.calculateRate}
            stateKey={'B'} val={this.state.currB} />
        </div>
      </div>
    );
  }
}

const Dropdown = props => (
  <select onChange={event => props.callbackFromParent(props.stateKey, event.target.value)}>
    <option value='cats'>Cats</option>
    <option value='dogs'>Dogs</option>
  </select>
)

export default App;