Javascript 如何区分调用回调函数的组件?

Javascript 如何区分调用回调函数的组件?,javascript,reactjs,Javascript,Reactjs,我是新手,如果这是个新问题,我很抱歉。我有一个组件下拉列表,它通过回调函数返回一个值。我想渲染两次,选择两个不同的值,然后简单地渲染下面选择的值。如何允许两个不同的组件向组件发送不同的数据。下面是我的代码 index.js import { Dropdown } from './components/dropdown' class App extends Component { constructor(props) { super(props); this.calculat

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

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;
从“/components/Dropdown”导入{Dropdown}
类应用程序扩展组件{
建造师(道具){
超级(道具);
this.calculateRate=this.calculateRate.bind(this);
this.callApi=this.callApi.bind(this);
此.state={
答复:“,
柯拉:0,
B:1
}
}
componentDidMount(){
这是callApi()
.then(res=>this.setState({response:res.express}))
.catch(err=>{console.log(err)});
}
callApi=async()=>{
const response=wait fetch('/main');
const body=wait response.json();
如果(response.status!==200)抛出错误(body.message);
返回体;
}
calculateRate=(键,值)=>{
//如果呼叫代理发送了currA数据,请更新currA,
//否则,如果呼叫代理发送了currB数据,请更新currB
if(key=='A')this.setState({currA:val})
if(key=='B')this.setState({currB:val})
console.log('updated curr'+key+'到'+val');
}
render(){
返回(
);
}
}
导出默认应用程序;
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>
    );
  }
}
导出类下拉列表扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
名单:[],
选定:“”
};
}
componentDidMount(){
取('https://api.fixer.io/latest')
.then(response=>response.json())
。然后(myJson=>{
this.setState({list:Object.keys(myJson.rates)});
});
}
render(){
var selectCurr=(curr)=>
props.callbackFromParent(props.stateKey,event.target.value)}
>
{(this.state.list).map(x=>{x})}
;
返回(
{selectCurr()}
);
}
}

我不确定您想要实现什么目标,但希望下面的内容能够说明如何允许两个不同的组件向
组件发送不同的数据

重要的变化是:我们需要将方法绑定到
构造函数()
函数中的
组件,然后我们可以使用
下拉列表中的
.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;
import React,{Component}来自'React';
导入“/App.css”;
类应用程序扩展组件{
建造师(道具){
超级(道具);
this.calculateRate=this.calculateRate.bind(this);
this.callApi=this.callApi.bind(this);
此.state={
答复:“,
柯拉:0,
B:1
}
}
componentDidMount(){
/*
这是callApi()
.then(res=>this.setState({response:res.express}))
.catch(err=>{console.log(err)});
*/
}
callApi=async()=>{
const response=wait fetch('/main');
const body=wait response.json();
如果(response.status!==200)抛出错误(body.message);
返回体;
}
calculateRate=(键,值)=>{
//如果呼叫代理发送了currA数据,请更新currA,
//否则,如果呼叫代理发送了currB数据,请更新currB
if(key=='A')this.setState({currA:val})
if(key=='B')this.setState({currB:val})
console.log('updated curr'+key+'到'+val');
}
render(){
返回(
);
}
}
常量下拉列表=道具=>(
props.callbackFromParent(props.stateKey,event.target.value)}>
猫
狗
)
导出默认应用程序;

这正是我需要的,但似乎仍然不起作用。如您所示,我在我的dropdown.js组件中更改了index.js:this.props.callbackFromParent.bind(null,this.props.stateKey,event.target.value)}>,并在index.js{this.state.currA}{this.state.currB}

中添加了render()方法来简单地呈现新值。我没有得到任何结果。我无法计算…@Malvinka我更新了我的答案,使用了select。因为您在
onChange
回调函数中创建了一个匿名函数,所以只需将变量传递到回调函数中,而无需绑定这些变量。还请注意,下拉组件使用
props[propName]
访问道具,而不是
this.props[propName]
——上面更新的答案是否有帮助?