问题描述
我正处于学习React.js的早期阶段。 我正在尝试学习如何模块化React.js组件。
我将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);
1楼
测试了您提供的内容,因为它实际上看起来应该正确。
对其进行一些小的更改,使其可以在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测试您所做的事情,并考虑简化设置,直到可行为止,然后从那里开始。
进行良好的错误查找:)