【问题标题】:React.js onclick handler not workingReact.js onclick 处理程序不起作用
【发布时间】:2016-04-18 10:35:44
【问题描述】:

我在我的 node.js 应用程序中使用 react.js 作为模板库。我正在为我的反应组件使用 jsx 语法。我有一个类似 /entities 的路由,它呈现entities.jsx 文件(它是一个视图)。我的 entity.jsx 文件中有以下代码。我试图在我的代码中调用 onclickhandler,但它不起作用。我没有使用 React.render 显式渲染它,但是当我点击 localhost:/entities 但 onclick 处理程序没有触发时,组件显示在浏览器中。

  var MyComponent = React.createClass({
    alertMessage: function() {
       alert(this.props.name);                             
   },
    render: function () {
      return (
       <div onClick={this.alertMessage}>
        Hello {this.props.name}
       </div>
     );
    }
 });

我在网上看到的示例呈现嵌入在 html 中的 jsx 脚本和呈现在 html div 标签中的组件,但我试图在我的 node.js 应用程序中使用 react.js。我不想在 html 标记中呈现它,但组件应该基于 url 呈现并且应该是动态的

我的节点应用程序的 index.js 文件中有以下代码 sn-p 。我通过呈现视图实体的 index.js 文件点击视图“实体”。

app.get('/entities', function(req, res) {
  res.render('entities', {
    title: 'Entities - Turkey Disclosure',
    name: 'Entities',
    selection: 'header-entities'
  });
});

【问题讨论】:

  • 那行不通。显然这仅适用于 ES6 语法
  • 您的示例按预期工作fiddle
  • 我没有使用 React.render。当我这样做时,我收到一条错误消息,提示 ReferenceError:document is not defined
  • 如何渲染组件?你能添加代码示例吗?
  • @The ..请看编辑

标签: node.js reactjs


【解决方案1】:

如果我猜对了,您正在使用 React.renderToString() 在节点应用程序中呈现反应。 React 不会将onClick 和其他事件语句直接插入到标记中。如果你想保留这些事件,你应该在已经有服务器渲染标记的节点上调用React.render()。 React 将保留它并仅附加事件处理程序,让您获得非常高效的首次加载体验。

There's a nice article 解释 React 中三种渲染方法的区别。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多