简体   繁体   English

React.Component-由new运算符创建的重用组件

[英]React.Component - reuse component created by `new` operator

I am new to ReactJS, I was wondering if we reuse an already created React.Component (by new operator) inside render method. 我是ReactJS的新手,我想知道我们是否在render方法中重用(由new操作员创建的) React.Component For example - 例如 -

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

        <script src="react.16.8.6.development.js"></script>
        <script src="react-dom.16.8.6.development.js"></script>
        <script src="babel.7.5.4.min.js"></script>
    </head>

    <body>
        <br>
        <h3>Enter number in box for multiplication.</h3>
        <br>
        <div id="container"></div>
        <script type="text/babel">

            class ResultComp extends React.Component{
                constructor(props){
                    super(props)
                    this.state = {valueOne : 0, valueTwo : 0, product : 0}
                }
                render(){
                    console.log("ResultComp : render")
                    return(
                        <div>Result = {this.state.product}</div>
                    )
                }
            }

            class MyApp extends React.Component{
                render(){
                    console.log("MyApp : render")
                    var alreadyCreatedComponent = new ResultComp()
                    return (
                        <div>
                            <ResultComp id="0"/>
                            <alreadyCreatedComponent id="2"/> 
                            <br/>
                        </div>
                    )
                }
            }

            ReactDOM.render(
                <MyApp/>,
                document.getElementById("container")
            )
        </script>
    </body>
</html>

Here - <ResultComp id="0"/> is working. 在这里- <ResultComp id="0"/>正在工作。

But, can we make something like <alreadyCreatedComponent id="2"/> ? 但是,我们可以制作类似<alreadyCreatedComponent id="2"/>吗?

I need to do this, because I need to pass the same alreadyCreatedComponent to some other function. 我需要这样做,因为我需要将相同的alreadyCreatedComponent传递给其他函数。

This is what React JS is for. 这就是React JS的目的。 You don't need the following: 您不需要以下内容:

var alreadyCreatedComponent = new ResultComp()

Instead, what you can do is: 相反,您可以做的是:

return (
    <div>
        <ResultComp id="0"/>
        <ResultComp id="2"/> 
        <br/>
    </div>
);

But if you want to use the same state values, you have to step the states location up in the parent component and pass them as props. 但是,如果要使用相同的状态值,则必须在父组件中向上移动状态位置,并将它们作为道具传递。

That's the reusing of components in React JS. 那就是React JS中组件的重用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM