无法从 React Js 按钮单击调用函数

我有 Message.js -


import React from 'react';

import { Button } from 'reactstrap';

class Message extends React.Component

{

    constructor()

    {

super()

this.state={

    message:"This is message"

}

    }

    changeMessage() {

        alert("In");

        this.setState({

            message :"message changed"

        });

    }

    render=()=> {

        return <div>

            <h1>{this.state.message}</h1>

            <Button onClick="{this.changeMessage}" color="success">success</Button>

        </div>

    }

}

export default Message

按钮点击在这里不起作用。我尝试过 -


<Button onClick={changeMessage} color="success">success</Button>

然后也尝试过 -


<Button onClick="changeMessage()" color="success">success</Button>

这也行不通。

http://img3.mukewang.com/64a68646000115b006100333.jpg

Uncaught TypeError : this.props.onClick is not a function.



慕沐林林
浏览 169回答 5
5回答

摇曳的蔷薇

class Message extends React.Component {  constructor() {    super();    this.state = {      message: "This is message",    };  }  changeMessage = () => {    alert("In");    this.setState({      message: "message changed",    });  };  render = () => {    return (      <div>        <h1>{this.state.message}</h1>        <button onClick={this.changeMessage} color="success">          success        </button>      </div>    );  };}export default Message;

慕容3067478

onClick={this.changeMessage}&nbsp;need&nbsp;not&nbsp;to&nbsp;be&nbsp;a&nbsp;string&nbsp;.尝试这个 :<Button&nbsp;onClick={()=>this.changeMessage()}&nbsp;color="success">success</Button>

慕丝7291255

您传递的 onClick 应该是一个函数,并且该函数必须绑定到在“&nbsp;changeMessage ”函数内使用“&nbsp;this&nbsp;”指针,因此您可以尝试使用如下,<Button&nbsp;onClick={this.changeMessage.bind(this)}&nbsp;color="success">success</Button>

肥皂起泡泡

<Button onClick={this.changeMessage} color="success">success</Button><Button onClick={() => {this.changeMessage(your params)}} color="success">success</Button>

慕姐4208626

你不需要在reactjs中引用函数。就这样分配吧。<Button onClick={this.changeMessage} color="success">success</Button>和功能changeMessage = () => {&nbsp; &nbsp; &nbsp; &nbsp; alert("In");&nbsp; &nbsp; &nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; message :"message changed"&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript