反应按钮单击事件未触发-一个按钮有效,一个按钮无效

时间:2019-06-18 12:17:07

标签: html reactjs button

我希望有人能帮助我。我在react组件中有两个按钮。它们都调用相同的javascript函数。一个按钮有效,而另一个按钮无效。谁能帮我解释发生了什么事?

我已将代码简化为最小的单位,以证明该问题。

这是“ react.buttonClickComponent.js”文件:

class ButtonClick extends React.Component {

    constructor(props) {
        super(props);
    }

    componentDidMount() {
        console.log("componentDidMount");
    }

    buttonClickLaser = () => {
        console.log("buttonClickLaser()");
    }

    render() {
        console.log("inside render");

        return (
            <div>
                <button onclick={this.buttonClickLaser} >Button 1 - Doesnt Work</button>

                <button class="btn btn-default" onClick={this.buttonClickLaser}>Button 2 - This Button Works! <span class="glyphicon glyphicon-fast-forward"></span></button>

            </div>
        )
    }
}

我希望两个按钮都调用函数buttonclickLaser(),但按钮1无效!

这是调用react组件的HTML文件:

<html>
<head>
    <script type="application/javascript" src="https://unpkg.com/react@16.0.0/umd/react.production.min.js"></script>
    <script type="application/javascript" src="https://unpkg.com/react-dom@16.0.0/umd/react-dom.production.min.js"></script>
    <script type="application/javascript" src="https://unpkg.com/babel-standalone@6.26.0/babel.js"></script>

    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <script type="application/javascript" src="https://unpkg.com/jquery@3.3.1/dist/jquery.min.js"></script>
    <script type="application/javascript" src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

    <script type="text/babel" src="react.buttonClickComponent.js" crossorigin="anonymous"></script>
</head>
<body>  
    <div id="app"></div>

    <script type="text/babel">

        $(document).ready(function () {
            console.log("document loaded");
            ReactDOM.render(<ButtonClick />, document.getElementById('app'));
        });

    </script>
</body>
</html>

1 个答案:

答案 0 :(得分:4)

错误为onclick,请使用onClick

 <button onClick={this.buttonClickLaser} >Button 1 - Doesnt Work</button>