【发布时间】: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