【问题标题】:how to distinguish which component called a callback function?如何区分哪个组件调用了回调函数?
【发布时间】:2018-03-29 20:54:37
【问题描述】:

我是新来的反应,对不起,如果这是新问题。我有一个下拉组件,它通过回调函数返回一个值。我想渲染两次以选择两个不同的值,然后简单地在下面渲染选择的值。我怎样才能让你的两个不同的组件向组件发送不同的数据。下面是我的代码。

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>
    );
  }
}

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    我不确定您要实现什么,但希望以下内容显示您如何允许两个不同的组件将不同的数据发送到 &lt;App&gt; 组件。

    重要的变化是:我们需要将方法绑定到constructor()函数中的&lt;App&gt;组件,然后我们可以使用Dropdown组件中的.bind()方法来指定要传入回调的数据功能:

    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;
    

    【讨论】:

    • 这正是我需要的,但似乎仍然无法正常工作。我在我的 dropdown.js 组件中更改了 index.js,如您在此处显示的那样:
    • @Malvinka 我更新了我的答案以使用选择。因为您在onChange 回调中创建了一个匿名函数,所以您只需将变量传递给回调函数而不绑定这些变量。另请注意,Dropdown 组件使用props[propName] 而不是this.props[propName] 访问道具——上面更新的答案有帮助吗?
    猜你喜欢
    • 2012-10-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多