【发布时间】:2021-02-28 18:31:37
【问题描述】:
我正在制作一个大学注册网站,我正在尝试制作一个列表,让学生可以选择某个专业来查看其中的所有课程,所以我制作了一个列表,其中包含所有专业和前面的按钮,但每次我尝试使用onClick() 函数转到另一个页面,其中包含undefined 的课程列表。
我的代码:
import React, { Component } from 'react';
import axios from 'axios';
import { Table } from 'react-bootstrap'
import { Button, Icon } from 'semantic-ui-react';
import { Image, List } from 'semantic-ui-react'
import { left } from '@popperjs/core';
export default class CreateExercise extends Component {
constructor(props) {
super(props);
this.onClick = this.onClick.bind(this);
}
onClick(e) {
window.location = '/' + e
}
render() {
return (
<div>
<ul>
{['Adolescence Education: Chemistry (7-12)',
'Adolescence Education: Social Studies (7-12)',
'Biological Sciences',
'Chemistry',
'English',
'History',
'Industrial and Labor Relations',
'Liberal Arts',
'Media and Communications',
'Philosophy and Religion',
'Politics & Economics & Law',
'Spanish Language',
'Visual Arts',
'Adolescence Education: Biology (7-12)',
'Adolescence Education: Mathematics (7-12)',
'Biochemistry',
'Business Administration',
'Childhood Education (1-6)',
'Computer & Information Science',
'Criminology',
'Finance',
'General Studies',
'Health and Society',
'Industrial and Labor Relations',
'Management Information Systems',
'Marketing',
'Mathematics',
'Psychology',
'Sociology',
'Special Education and Childhood Education (1-6)',
'Visual Arts: Electronic Media'
].map(function (item) {
return (
<li key={item}>
{item}
<button type="button" type="button" onClick={onClick({ item })} style={{ position: 'absolute', left: '50%' }} >Click to view courses</button>
</li>
);
})}
</ul>
</div>
)
}
}
【问题讨论】:
-
在componentWillMount钩子里做
-
onClick={onClick({ item })}应该是onClick={()=>this.onClick(item)} -
@DanielCheung 我得到 TypeError: Cannot read property 'onClick' of undefined
-
@esmailsaba 抱歉,我在您阅读后删除了我的评论。 Lakshya 的回答是正确的。原因是
onClick没有定义为变量,而是this的属性。 -
@Solvenc1no 你能详细说明一下吗?
标签: javascript reactjs