如何从ReactJS中的onClick函数调用另一个组件
问题描述:
我正在学习Reactjs。我已经使用rails实现了一个示例反应应用程序。我有很多搜索找到解决方案,但我没有找到任何。我想从onClick
函数中调用另一个组件。但没有发生。这可能是我尝试实现的目标吗?如果是,那么请指出我在哪里犯错,如果不是,那么我可以采用哪种方式实施。这里是我的代码:如何从ReactJS中的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));
}
任何其他细节,如果你需要的话可以随意问。提前致谢:)
答
也许这个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
它希望这会有所帮助。
此外,您可以使用容器组件并将它用作两个组件之间的桥梁。
您是否在使用助焊剂或回流?目前,我正在与回流,我用商店来实现这一目标。 – dobleUber
@melaspelas:不,我不使用助焊剂。简单reactjs –
你试过https://facebook.github.io/react/tips/communicate-between-components.html ?? – dobleUber