我正在学习Reactjs。我用rails实现了一个示例反应应用程序。我经常搜索找到解决方案,但我找不到任何解决办法。我想从onClick
函数调用另一个组件。但什么都没发生。这可能是我试图实现的吗?如果是,那么请指出我错误的地方,如果没有,那么我可以实施哪种方式。这是我的代码:
var Comment = React.createClass({
render: function () {
return (
<div id={"comment_"+ this.props.id }>
<h4>{ this.props.author } said:</h4>
<p>{ this.props.desc }</p>
<a href='' onClick={this.handleDelete}>Delete</a> | #this is for delete which works great
<a href='' onClick={this.handleEdit}>Edit</a>
# If I put here then it works fine <UpdateComments comments={ this.props} /> but I don't want it here
</div>
)
},
handleDelete: function(event) {
$.ajax({
url: '/comments/'+ this.props.id,
type: "DELETE",
dataType: "json",
success: function (data) {
this.setState({ comments: data });
}.bind(this)
});
},
handleEdit: function(event) {
var Temp = React.createClass({
render: function(event){
return(<div>
<UpdateComments comments={ this.props} /> #here I want to call UpdateComments component
</div>
)
}
});
}
});
更新 如果我尝试下面的技巧,那么它调用组件但重新加载页面并再次消失称为组件:(
handleEdit: function() {
React.render(<UpdateComments comments={ this.props} /> , document.getElementById('comment_'+ this.props.id));
}
如果您需要任何其他细节,请随时询问。提前致谢。 :)
答案 0 :(得分:4)
也许这fiddle可以指出正确的方式
var Hello = React.createClass({
render: function() {
return <div>Hello {this.props.name}
<First1/>
<First2/>
</div>;
}
});
var First1 = React.createClass({
myClick: function(){
alert('Show 1');
changeFirst();
},
render: function() {
return <a onClick={this.myClick}> Saludo</a>;
}
});
var First2 = React.createClass({
getInitialState: function(){
return {myState: ''};
},
componentDidMount: function() {
var me = this;
window.changeFirst = function() {
me.setState({'myState': 'Hey!!!'})
}
},
componentWillUnmount: function() {
window.changeFirst = null;
},
render: function() {
return <span> Saludo {this.state.myState}</span>;
}
});
React.render(<Hello name="World" />, document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.1/react-with-addons.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.1/JSXTransformer.js"></script>
<script src="https://facebook.github.io/react/js/jsfiddle-integration.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
基本上我使用这些链接:
communicate between components
希望这会有所帮助。
此外,您可以使用容器组件并将其用作两个组件之间的桥梁。