How to call another component from onClick function in ReactJS

前端 未结 1 802
醉梦人生
醉梦人生 2021-02-04 18:57

I am learning Reactjs. I have implemented one sample react app with rails. I have search a lots to find the solution but I didn\'t find any. I wanted to call another component

相关标签:
1条回答
  • 2021-02-04 19:24

    Maybe this fiddle could point you in right way

    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>

    Basically I use those links:

    communicate between components

    dom event listeners

    It hopes this helps.

    Also, you could use the container component and use it like a bridge between both components.

    0 讨论(0)
提交回复
热议问题