【问题标题】:Unable to call function from component react [duplicate]无法从组件反应调用函数[重复]
【发布时间】:2023-03-17 11:28:01
【问题描述】:

这是我的组件

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。下拉选项是使用名为 items 的数组上的 map 函数创建的。

每个人都被分配了一个 ID,一个值 == 到它的内容,最后被赋予一个 onClick。所以在 dom 上他们都应该调用 handleClick() 。

问题是“handleClick”未定义。我看不出来是怎么回事,我已经在render函数上面明确定义了。我在反应中遗漏了一些关于范围的东西吗?我在谷歌上找不到任何答案,因为这是一个非常具体的问题。

谢谢大家,任何正确方向的指点将不胜感激。

【问题讨论】:

  • this.handleClick
  • 我试过了,还是未定义。
  • 另外,在地图调用中使用箭头功能
  • 仍然未定义:/ {items.map(function(name, index){ handleClick = () => { console.log('点击发生'); } return })}
  • 您应该使用this.handleClick 并在地图中使用箭头函数 {items.map((name, index) => { return })}

标签: javascript reactjs


【解决方案1】:

你在&lt;option key={ index } id={ index } value={ name } onClick = {this.handleClick} &gt;{ name }&lt;/option&gt;中错过了this

【讨论】:

  • 不幸的是我已经尝试过了,它仍然未定义。
  • 因为你绑定了 setState 而不是 handleClick。前者是反模式,后者是你需要的。
  • 好的所以我试过了:this.handleClick = this.handleClick.bind(this);我仍然不确定?
  • 你不必绑定handleClick,因为箭头函数上下文是自动绑定的
猜你喜欢
  • 1970-01-01
  • 2020-04-04
  • 2015-12-06
  • 1970-01-01
  • 2020-05-05
  • 2017-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多