【发布时间】:2018-02-16 12:31:57
【问题描述】:
这里有点 React 菜鸟,我已经搜索了相当多的解决方案来解决这个问题,但我仍然感到困惑。简而言之,我有一个带有数字列表的下拉菜单,通过映射从数组呈现。目的是能够通过单击下拉菜单中的按钮之一来通过 setState 更改“coloursValue”的值。一切都正确呈现,但是当我尝试单击其中一个按钮时,我遇到了错误消息“TypeError:无法读取未定义的属性'changeValue'”。我知道这可能是与范围有关的问题,并且“this”没有正确定义,但 changeValue 绑定在构造函数中。我做错了什么,我该如何纠正?
非常感谢您。
let colours = [1, 2, 3, 4, 5];
let coloursMapped = mapItems(colours, "coloursValue");
function mapItems(input, context) {
let listItems = input.map(item =>
<DropdownItem key={item}>
<button onClick={() => this.changeValue.bind(this)}>
{item}
</button>
</DropdownItem>
);
return <DropdownMenu right>
{listItems}
</DropdownMenu>
}
class App extends Component {
constructor(props) {
super(props);
this.changeValue = this.changeValue.bind(this);
this.toggle = this.toggle.bind(this);
this.state = {
coloursValue: "# of Colours",
dropdownOpen: [false, false, false]
};
}
changeValue(value, context) {
// modify "coloursValue" via setState according to the number
// selected via the "onClick" handler in "mapItems"
}
toggle(index) {
let dropdownState = this.state.dropdownOpen.slice();
dropdownState[index] = !this.state.dropdownOpen[index];
this.setState({
dropdownOpen: dropdownState
});
}
【问题讨论】:
-
“我做错了什么” 当你以“正常”的方式调用函数时,即
foo(),那么this要么指全局对象,要么@ 987654324@ 在严格模式下。因此,当您调用mapItems(colours, "coloursValue");时,this是undefined,因此this在() => this.changeValue.bind(this)中是undefined(顺便说一句,它甚至没有调用this.changeValue)。基本上,您试图在组件实例存在之前引用它。
标签: javascript reactjs reactstrap