如何进行跨组件调用?

时间:2017-01-22 14:09:22

标签: reactjs

我在两个单独的jsx文件上有以下两个组件

1。在Component1.jsx

    var Comp1 = React.createClass({
          componentDidMount: function() {
            this.comp1Fn();
          },
          comp1Fn: function() {
            console.log('Component 1 created');
            test1();
          },
          render: function() {
              return ( < div > < input type = "button"
                value = "Componenet 1" / > < /div>)
        }
    })

    function test1(){
        console.log('called test1');
    }


    var c1= ReactDOM.render(<Comp1 / > ,
                document.getElementById('div1'));

2。在Component2.jsx

var Comp2 = React.createClass({
    componentDidMount:function(){
        this.comp2Fn();
    },
    comp2Fn:function(){
        console.log('trying to call comp1fn function of Component 1');
        c1.comp1Fn(); //****calling the function comp1Fn of the Comp1*****
    },
    render:function(){
        return(<div><input type="button" value="Component 2"  /></div>)
    }
})


var c2= ReactDOM.render(<Comp2 />,
    document.getElementById('div2'))

以下是HTML:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head lang="en">
</head>
<body>   
<div id="div1"></div>
<div id="div2"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
<script type="text/babel" src="Component1.jsx"></script>
<script type="text/babel" src="Component2.jsx"></script>

</body>
</html>

在Comp2的comp2Fn()中,它会调用c1.comp1Fn()。但它给出了以下错误:

  

未捕获的ReferenceError:未定义c1       在Constructor.comp2Fn(eval at n.run(browser.min.js:3),:12:9)       在Constructor.componentDidMount(eval at n.run(browser.min.js:3),:8:14)       在CallbackQueue.notifyAll(react.js:839)       在ReactReconcileTransaction.close(react.js:12909)       在ReactReconcileTransaction.closeAll(react.js:16039)       在ReactReconcileTransaction.perform(react.js:15986)       at batchedMountComponentIntoNode(react.js:11190)       在ReactDefaultBatchingStrategyTransaction.perform(react.js:15973)       at Object.batchedUpdates(react.js:9229)       在Object.batchedUpdates(react.js:13702)

enter image description here

  1. 为什么我无法访问comp1Fn()的{​​{1}}函数?
  2. 如何从Comp2拨打Comp1

1 个答案:

答案 0 :(得分:0)

如果要在Comp2中访问Comp1,只需导出Comp1并导入到Comp2。

例如

export default Comp1
// Then import to Comp2
import Comp1 from 'your/path/to/Comp1

然后您可以访问Comp2中的Comp1