在ReactJs中内联到组件的“未定义函数” onClick函数吗?

我在reactJs中创建了come组件,由2个按钮处理每个onClick函数组成,但是当我运行代码“ myfunction is not defined”时出现错误。我想在按钮触发时将页面重定向到指定的地址。我的代码有什么问题?


import React, { Component } from 'react';

import { Link } from 'react-router-dom';


class MainMenu extends React.Component {

  constructor(props){

    super(props);

    this.slotClick = this.slotClick.bind(this);

    this.freqClick = this.freqClick.bind(this);

  }

   slotClick = (e) => {

    e.preventDefault();    

  }

   freqClick = (e) => {

    e.preventDefault();

  }

  render() {

    return (

      <div>   

        <input type="button" value="By Time Slot" onClick={ slotClick } />

        <input type="button" value="By Frequency" onClick={ freqClick } />

      </div>

    )

  }

}


export default MainMenu;


猛跑小猪
浏览 130回答 2
2回答

慕神8447489

您需要从访问功能this。而且您也不需要,bind()因为这些功能是箭头功能。render() {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; <input type="button" value="By Time Slot" onClick={ this.slotClick } />&nbsp; &nbsp; &nbsp; &nbsp; <input type="button" value="By Frequency" onClick={ this.freqClick } />&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; )&nbsp; }

慕码人8056858

您需要this在内使用class component。当我们使用时,我们arrow function不需要绑定功能import React, { Component } from 'react';import { Link } from 'react-router-dom';class MainMenu extends React.Component {&nbsp; constructor(props){&nbsp; &nbsp; super(props);&nbsp; }&nbsp; &nbsp;slotClick = e => {&nbsp; &nbsp; e.preventDefault();&nbsp; &nbsp;&nbsp;&nbsp; }&nbsp; &nbsp;freqClick = e => {&nbsp; &nbsp; e.preventDefault();&nbsp; }&nbsp; render() {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; <input type="button" value="By Time Slot" onClick={this.slotClick()} />&nbsp; &nbsp; &nbsp; &nbsp; <input type="button" value="By Frequency" onClick={this.freqClick()} />&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; )&nbsp; }}export default MainMenu;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript