重建 ReactJs 组件

IT技术 reactjs components mount rebuild
2021-05-25 05:30:53

我的应用程序中有一个 reactjs 组件(compA),它调用另一个 reactjs 组件(compB)来挂载 compA。

在 compB 中,我有一个按钮,在函数“componentDidUpdate”中,我需要销毁和重建 compA。

任何人都知道如何做到这一点?


大概的代码是这样的,但是,在我的代码 compA 和 B 中,它们位于不同的文件中。

use strict';

var CompA = React.createClass({
    getDefaultProps: function() {
        return {
            name: 'location',
        }
    },
    render: function () {
        return <CompB name={this.props.name}/>;
    }
});

var CompB = React.createClass({
    getDefaultProps: function() {
        return {
            name: 'select'
        }
    },
    componentDidUpdate: function() {
        $('.button').click(function() {
            /*
             * RELOAD HERE COMPONENT
             */
        });
    },
    render: function () {
        return <div><select name={this.props.name}><option value="x">X</option><option value="y">Y</option></select><button id="button">Reload</button></div>
    }
});

ReactDOM.render(<CompA />, document.getElementsByID("compA"));
<html>
<body>
  <div id="compA"></div>

  <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/js/bootstrap.min.js"></script>
  <script src="https://fb.me/react-0.14.7.js"></script>
  <script src="https://fb.me/react-dom-0.14.7.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>

  <script src="comp.jsx" type="text/jsx"></script>
</body>

1个回答

您不能从 CompB 重建整个 CompA,但从 CompB 调用 setState 将重建 CompB,在您的情况下,将重建整个 CompA(因为您在其中没有任何其他内容)。

如果你想从 Ajax 源重建一个组件,你可以看看: React Js:如何重新加载通过 ajax 加载的 initila 数据?