React.js - 作为CommonJS模块的组件 - 事件不起作用
问题描述:
我处于学习React.js的最初阶段。我试图学习如何模块化React.js组件。React.js - 作为CommonJS模块的组件 - 事件不起作用
我制作了一个React.js组件作为CommonJS模块,当我从其他模块调用它时 - 除了在组件重新呈现后状态变化。
我把我的代码放在最后。
我已将TestComponent
的代码放在文件名component.jspx
中。然后我使用的组件app.js
根据TestComponent
中的代码,它的initialState组件上将有两个列表项(带有一个触发事件的按钮)。
然后在componentDidMount
,我用一个额外的数据改变状态。
组件正确呈现 - 除了事件handleClickEvenet
似乎没有为更新的视图绑定。
请帮我理解如何解决这个问题。
//
// component.jsx
var TestComponent =React.createClass({
handleClickEvent: function() {
alert ('Clicked...');
},
getInitialState: function() {
return {
comments: [
{author: 'A1', comment: 'Comment by A1'},
{author: 'A2', comment: 'Comment by A2'}
]
};
},
componentDidMount: function() {
var comments = this.state.comments;
comments.push({author: 'A3', comment: 'Comment by A3'});
this.setState({comments: comments});
},
render: function() {
var thisComponent = this;
return (
<ol>
{
this.state.comments.map (function(comment, i) {
return (
<li>
{comment.comment} | {comment.author} |
<button onClick={thisComponent.handleClickEvent}>Click me</button>
</li>
)
})
}
</ol>
)
}
})
module.exports = TestComponent;
// -------
// app.js
// -------
var CommentBox = require('./components/Demo.jsx');
var React = require('../components/react/react-with-addons.js');
var commentBox = React.createElement(CommentBox, data);
React.render(commentBox, document.body);
答
测试了你提供的东西,因为它实际上看起来应该如此。
做给它一些小的改动,以便它可以在执行的jsfiddle,它应该像这样(jsfiddle):
var CommentBox = React.createClass({
handleClickEvent: function() {
alert ('Clicked...');
},
getInitialState: function() {
return {
comments: [
{author: 'A1', comment: 'Comment by A1'},
{author: 'A2', comment: 'Comment by A2'}
]
};
},
componentDidMount: function() {
var comments = this.state.comments;
comments.push({author: 'A3', comment: 'Comment by A3'});
this.setState({comments: comments});
},
render: function() {
var thisComponent = this;
return (
<ol>
{
this.state.comments.map (function(comment, i) {
return (
<li>
{comment.comment} | {comment.author} |
<button onClick={thisComponent.handleClickEvent}>Click me</button>
</li>
)
})
}
</ol>
)
}
});
var commentBox = React.createElement(CommentBox, {});
React.render(commentBox, document.body);
我想这个问题是次要的东西,并没有什么大的。使用提供的jsfiddle测试你做了什么,并考虑简化你的设置,直到它工作并从那里取出。
有一个很好的错误狩猎:)
嗨Emil, 感谢您关注它。 我知道它适用于JSFiddle - 因为组件和调用都发生在一个文件中。 但我刚刚提到的问题只有当我使用module.exports导出React组件时。然后在不同的文件中使用它。 – Ananth