简体   繁体   中英

I have two components. I want to call 1st component into the second component. How can I do it?

I have two components. I want to call 2nd component into the first component component

//first component

import React, { Component } from "react";

class Admin extends Component {
  render() {
    return (
      <div>
        <button>admin login</button>
      </div>
    );
  }
}
export default Admin;

...

//2nd component

import React, { Component } from "react";
import Admin from "./components/Admin";

class Main extends Component {
  render() {
    return (
      <div>
        <p>main page</p>

        <Admin />
      </div>
    );
  }
}
export default Main;

if you want the second component in the first component just import it and place it in the div

import React, { Component } from "react";
import Main from "./components/Main"

    class Admin extends Component {
      render() {
        return (
          <div>
            <button>admin login</button>
            <Main/>
          </div>
        );
      }
    }
    export default Admin;

But doing that you will have to take Admin out of the Main component:

import React, { Component } from "react";


class Main extends Component {
  render() {
    return (
      <div>
        <p>main page</p>


      </div>
    );
  }
}
export default Main;

Not sure if I am understanding this correctly, but since you've loaded the 1st Component () into the 2nd component already, I would expect that trying to call the second one into the first will cause an error due to an infinite import issue.

If you only want the second component in the first, but not first in the second, then the answer by Brad Ball should work.

Taking a look at the code you're presenting to us, we can see you're invoking Admin as a Child Component of Main.

@Brad Ball gave you the inverse, invoking Main as a Child Component of Admin.

If you want to compose them one needs to be the parent, the other the child.

If you want them to be siblings you need a third component to be the parent of both.

Can you explain better what you want to do?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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