JS/React - 无法读取未定义的 属性 "X",无法访问方法
JS/React - cannot read property "X" of undefined, unable to access method
这里有点 React 新手,我已经搜索了很多关于这个问题的解决方案,但我仍然感到困惑。简而言之,我有一个带有数字列表的下拉菜单,通过地图从数组中呈现。目的是能够通过单击下拉菜单中的按钮之一通过 setState 更改 "coloursValue" 的值。一切都正确呈现,但是当我尝试单击其中一个按钮时,我遇到了错误消息 "TypeError: Cannot read property 'changeValue' of undefined"。我知道这可能是与范围和 "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
});
}
这是因为 mapItems
存在于 class 之外,所以它无法访问 class 范围来绑定 changeValue
。将 mapItems
移动到 App
组件中,它应该可以工作。您还应该将 colours
和 coloursMapped
作为状态移动到 App
组件中。
这里有点 React 新手,我已经搜索了很多关于这个问题的解决方案,但我仍然感到困惑。简而言之,我有一个带有数字列表的下拉菜单,通过地图从数组中呈现。目的是能够通过单击下拉菜单中的按钮之一通过 setState 更改 "coloursValue" 的值。一切都正确呈现,但是当我尝试单击其中一个按钮时,我遇到了错误消息 "TypeError: Cannot read property 'changeValue' of undefined"。我知道这可能是与范围和 "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
});
}
这是因为 mapItems
存在于 class 之外,所以它无法访问 class 范围来绑定 changeValue
。将 mapItems
移动到 App
组件中,它应该可以工作。您还应该将 colours
和 coloursMapped
作为状态移动到 App
组件中。