Как загрузить новый компонент по нажатию кнопки в ReactJs? - PullRequest
0 голосов
/ 14 января 2019

Я создал основной компонент в ReactJs под названием MainPage (используя Material-UI).

import React from 'react';
import Grid from '@material-ui/core/Grid';
import Button from '@material-ui/core/Button';
import CssBaseline from '@material-ui/core/CssBaseline';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import withStyles from '@material-ui/core/styles/withStyles';

const styles = theme => ({
    card: {
        minWidth: 350,
    },
    button: {
        fontSize: '12px',
        margin: theme.spacing.unit,
        minWidth: 350
    },
    extendedIcon: {
        marginRight: theme.spacing.unit,
    }
});

class MainPage extends React.Component {
    constructor() {
        super();
    }

    render() {
        const {
            classes
        } = this.props;

        return ( <
            React.Fragment >
            <
            CssBaseline / >
            <
            Grid container spacing = {
                0
            }
            direction = "column"
            alignItems = "center"
            justify = "center"
            style = {
                {
                    minHeight: '100vh'
                }
            } >
            <
            form onSubmit = {
                this.handleSubmit
            } >
            <
            Card className = {
                classes.card
            } >
            <
            CardContent >
            <
            Grid item xs = {
                3
            } >
            <
            Button variant = "contained"
            size = "medium"
            color = "primary"
            className = {
                classes.button
            }
            type = "submit"
            value = "single" >
            ButtonA <
            /Button> <
            /Grid> <
            Grid item xs = {
                3
            } >
            <
            Button variant = "contained"
            size = "medium"
            color = "primary"
            className = {
                classes.button
            }
            type = "submit"
            value = "batch" >
            ButtonB <
            /Button> <
            /Grid> <
            /CardContent> <
            /Card> <
            /form> <
            /Grid> <
            /React.Fragment>
        );
    }
}

export default withStyles(styles)(MainPage);

Я хочу загрузить новый компонент (CompA или CompB, в зависимости от того, какая кнопка была нажата - ButtonA или ButtonB) при нажатии кнопки. Новый компонент должен полностью заменить текущий компонент - я имею в виду, что он должен быть загружен на весь экран (а не рядом с кнопками).

Как я могу это сделать?

UPDATE:

Я хочу заменить компонент MainPage, а не просто рендерить поверх него.

Вот как я загружаю MainPage:

index.js

import React from 'react';
import { render } from 'react-dom';
import MainPage from './components/MainPage';

const View = () => (
  <div>
    <MainPage/>
  </div>
);

render(<View />, document.getElementById('root'));

Ответы [ 2 ]

0 голосов
/ 14 января 2019

В вашем index.js вы можете использовать

const View = () => (
  <div>
    <MainPage condition='something' />
  </div>
);

Тогда на вашей главной странице:

class MainPage extends React.Component {
   constructor() {
      super();
   }

  myCondition1() {
    return (
        <Component1 />
    );
 }


  myCondition2() {
    return (
        <Component2 />
    );
 }

  render() {
     const { condition} = this.props;
     return (
         {condition === 'something' ? this.myCondition1() : this.myCondition2()}
     )
  }
}

UPDATE

Вот пример с простой кнопкой:

class Condition1 extends React.Component {
  render() {
    return (
        <div>Condition 1</div>
    );
  }
}

class Condition2 extends React.Component {
  render() {
    return (
        <div>Condition 2</div>
    );
  }
}

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
          condition: true
        };
        this.handleClick = this.handleClick.bind(this);
    }
    
    handleClick(condition) {
      this.setState( {condition} )
    }

  render() {
     const { condition } = this.state;
     return (
         <div>
             <button onClick={() => this.handleClick(true)}>Condition1</button>
             <button onClick={() => this.handleClick(false)}>Condition2</button>
             {condition === true ? <Condition1 /> : <Condition2 />}
         </div>
     )
  }
}

ReactDOM.render( < App / > ,
  document.getElementById('root')
);
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script><div id="root" />
0 голосов
/ 14 января 2019

Вы можете создать другой компонент для обработки состояния и добавить оператор if в этот компонент для обработки представления, которое вы хотите отобразить.

Вы можете увидеть пример здесь codesandbox.io / embed / 6wx2rzjrr3

App.js

import React, { Component } from "react";
import ReactDOM from "react-dom";
import Main from "./Main";
import View1 from "./View1";
import View2 from "./View2";

import "./styles.css";

class App extends Component {
  state = {
    renderView: 0
  };

  clickBtn = e => {
    this.setState({
      renderView: +e.target.value
    });
  };

  render() {
    switch (this.state.renderView) {
      case 1:
        return <View1 />;
      case 2:
        return <View2 />;
      default:
        return <Main clickBtn={this.clickBtn} />;
    }
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Main.js

import React from "react";

export default props => (
  <>
    Main view{" "}
    <button value={1} onClick={props.clickBtn}>
      View 1
    </button>{" "}
    <button value={2} onClick={props.clickBtn}>
      View 2
    </button>{" "}
  </>
);

View1.js

import React from "react";

export default props => "View 1";

View2.js

import React from "react";

export default props => "View 2";
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...