[英]How to call another component from onClick function in ReactJS
我正在學習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));
}
如果您需要任何其他細節,請隨時詢問。 提前致謝。 :)
也許這個小提琴可以指出你正確的方式
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>
基本上我使用這些鏈接:
它希望這會有所幫助。
此外,您可以使用容器組件並將其用作兩個組件之間的橋梁。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.