不能让es6对绑定事件做出反应

时间:2016-05-05 17:38:37

标签: reactjs ecmascript-6

我将反应应用程序迁移到ES6并移动事件以便它们在构造函数中绑定,这是一个非常基本的示例:

import React from 'react';
import ReactDom from 'react-dom';

export default class Button extends React.Component {
    constructor() {
        super();
        this.click = this.click.bind(this);
    }
    click() {
        alert('hi');
    }
    render() {
        return (
            <button onClick={this.click}>click</button>
        );
    }
}

if(typeof window !== 'undefined') {
    ReactDom.render(<Button/>, document.getElementById('button-spot'));
}

按钮呈现正确,并且没有任何服务器/客户端错误,但是当我单击此按钮时,没有任何反应。我也试过console.log()并且没有记录。我在event.bind(this)绑定错误吗?

更多背景信息:

我的index.js路由器:

router.get('/', function(req, res, next) {
    res.render('index', { 
        button: ReactDom.renderToString(<Button/>)
    });
});

html页面:

<div id='button-spot'><%-button%></div>

修改

我在下面尝试了安德烈的建议

onClick={x => alert(1)}

并且事件没有解决,问题是什么?

1 个答案:

答案 0 :(得分:0)

不幸的是,在使用DOM事件处理程序时,您无法仅从服务器呈现React。您需要呈现客户端/服务器React代码或使用直接解决该问题的服务器端呈现解决方案。

以下是一些很好的起点: