无法从组件反应调用函数

时间:2018-10-16 09:41:54

标签: javascript reactjs

这是我的组件

import React from 'react';
import {ButtonDropdown, DropdownToggle, DropdownMenu, DropdownItem } from 'reactstrap';

var URL = "URL"

class DropDown extends React.Component {

  constructor(props) {
    super(props);
    this.setState = this.setState.bind(this)
    this.state = {
      returnedItems: [],
      SelectedItem: null
      
    }
  }

 

  componentDidMount() {
    fetch(URL)
      .then(res => res.json())
      .then(
        (result) => {
    
          this.setState({
           returnedItems: result.map(x => x["firstName"]),
          
          });
        },
      // need to handle the error like this or we'll end up catching react errors aswell. 
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      )
  }


  handleClick = () => {
    console.log('Click happened');
  }


       render(){
        var items = this.state.returnedItems
     

           return(

             <div> 
        
      
            <select id="Salesmen">
             
             {items.map(function(name, index){
              
              return <option key={ index } id={ index } value={ name } onClick = {handleClick}  >{ name }</option>
            })}
       
              
             </select>
      
           </div> 
           
     
           );
       }
   
      }



export default DropDown; 

基本上,我想做的就是对这些下拉选项中的任何一个执行handleClick函数onclick。使用map函数在名为items的数组上创建下拉选项。

每个人都为其分配一个ID,即其内容的值==,最后为其分配一个onClick。因此在dom上,它们都应该调用handleClick()。

问题是“ handleClick”未定义。我看不到它是什么,我已经在render函数上方明确定义了它。我在反应中是否缺少有关范围的信息?我在Google上找不到任何答案,因为这是一个非常具体的问题。

感谢所有朝着正确方向的指针。

1 个答案:

答案 0 :(得分:0)

您错过了this中的<option key={ index } id={ index } value={ name } onClick = {this.handleClick} >{ name }</option>

相关问题