Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Gustavo2503

Função dentro de função

Recommended Posts

Eu estou criando uma classe que cria modais usando React, eu preciso criar um modal dentro de um modal, para isso, eu quero chamar a mesma função dentro dela mesma. O modal é criado, mas o problema é que ele não abre, abre o modal principal (#modal-1), mas não abre o sub modal (#modal-2), veja como ficou meu código:

index.html

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Modal</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
    <script src="js/modal.js" type="text/babel"></script>
    <link rel="stylesheet" href="css/modal.css">
</head>
<body>

<div align="center">
    <h1>Modal</h1>
</div>

    <button type="button" data-modal="modal-1">Open Modal</button>
    <div id="modal-content"></div>

    <script type="text/babel">
        const contentSub = [
            <h2>Title SubModal 1</h2>,
            <p>SubModal</p>,
            <small>Rodapé submodal 1</small>
        ];
        const idSub = "modal-2";

        const content = [
            <h2>Title 1</h2>,
            <section>
                <button type="button" data-modal="modal-2">Open SubModal</button>
                <Modal id={idSub} content={contentSub}/>
            </section>,
            <small>Rodapé 1</small>
        ];

        const id = "modal-1";
        ReactDOM.render(
            <Modal id={id} content={content}/>,
            document.getElementById('modal-content')
        );
    </script>

</body>
</html>

js/modal.js

class Modal extends React.Component{
    constructor(props) {
        super(props);

        this.id = this.props.id;

        this.backgroudColorHeader = this.props.backgroudColorHeader === undefined ? 'rgba(103, 117, 240, 1)' : this.props.backgroudColorHeader;
        this.textColorHeader = this.props.textColorHeader === undefined ? '#fff' : this.props.textColorHeader;

        this.backgroudColorBody = this.props.backgroudColorBody === undefined ? 'rgba(255, 255, 255, 1)' : this.props.backgroudColorBody;
        this.textColorBody = this.props.textColorBody === undefined ? '#000' : this.props.textColorBody;

        this.backgroudColorFooter = this.props.backgroudColorFooter === undefined ? 'rgba(103, 117, 240, 1)' : this.props.backgroudColorFooter;
        this.textColorFooter = this.props.textColorFooter === undefined ? '#fff' : this.props.textColorFooter;

        this.borderRadius = this.props.borderRadius === undefined ? '8px' : this.props.borderRadius;

        this.content = this.props.content === undefined ? [<h2>header content</h2>, <p>body content</p>, <p>footer content</p>] : this.props.content;
        this.size = this.props.size === undefined ? 3 : this.props.size;
    }

    closeModal = () => {
        $('#'+this.id).removeClass("show");
        $('body').removeClass("overflow-hidden");
    };

    render(){
        $(`[data-modal]`).click( function () {
            var id = $(this).attr("data-modal");
            var el = document.getElementById(id);
            $(el).addClass("show");
            $('body').addClass("overflow-hidden");
        });

        var background,
            text;

        background = this.backgroudColorHeader;
        text = this.textColorHeader;
        const transparencyBackgroundHeader = background.substring(background.length-2,background.length-1) -.1;
        const backgroundColorHeader = `${background.substring(0,background.length-2)}${transparencyBackgroundHeader})`;
        const styleColorHeader = {
            backgroundColor: backgroundColorHeader,
            color: text,
            borderBottom: `1px solid ${background}`
        };

        background = this.backgroudColorBody;
        text = this.textColorBody;
        const styleColorBody = {
            backgroundColor: background,
            color: text
        };

        background = this.backgroudColorFooter;
        text = this.textColorFooter;
        const transparencyBackgroundFooter = background.substring(background.length-2,background.length-1) -.1;
        const backgroundColorFooter = `${background.substring(0,background.length-2)}${transparencyBackgroundFooter})`;
        const styleColorFooter = {
            backgroundColor: backgroundColorFooter,
            color: text,
            borderTop: `1px solid ${background}`
        };

        const styleBorderRadius = {borderRadius: this.borderRadius};

        const eDivision = ['h', 'b', 'f'];
        const eContent = this.content;
        var div = [];
        for (var i=0;i<eContent.length;i++){
            const part = eDivision[i].replace('h', 'header').replace('b', 'body').replace('f', 'footer')+"-modal";
            const closeModal = i === 0 ? <span onClick={this.closeModal} className="close-modal"><i className="material-icons">close</i></span> : "" ;

            var style;
            if (i===0) style = styleColorHeader;
            else if (i===1) style = styleColorBody;
            else style = styleColorFooter;
            div.push(<div key={i+1} className={part} style={style}>
                       {closeModal}
                       {eContent[i]}
                     </div>);
        }

        const eSize = this.size;
        const s = ['s', 'm-s', 'm', 'm-l', 'l'];
        const size = s[eSize-1];

        const classModal = (size !== "s" &&
            size !== "m-s" &&
            size !== "m" &&
            size !== "m-l" &&
            size !== "l") ? 'modal-modal modal-m' : "modal-modal modal-"+size;

        return <div id={this.id} className={classModal}>
                   <div className="overflow-modal">
                       <div className="container-modal" style={styleBorderRadius}>
                           {div}
                       </div>
                   </div>
               </div>;
    }
}

 

Compartilhar este post


Link para o post
Compartilhar em outros sites

  • Conteúdo Similar

    • Por Rafael_Ferreira
      Não consigo carregar a imagem do captcha do meu formulário. Foi testado com o xampp e easyphp. Também não carregou a imagem de outros captcha. 
       
       
    • Por luiz monteiro
      Olá.
      Estou atualizando meu conhecimento com Front-End e me deparei com o seguinte problema.
      Criei um sistema para fazer o upload de imagens e alguns campos text.
      Algo bem simples para depois começar a estudar javascript para mostrar a miniatura....
      Mas quando saio do navegador Chrome ou da aba por mais de 3 minutos, ao retornar o navegador as vezes atualiza ou nem chega atualizar mas limpa os campos.
      Estou usando um Smart Motorola com Android, mas um amigo testou no iPhone e acontece a mesma coisa.
      Gostaria de saber se há como usar javascript para evitar isso?
      Agradeço desde já.

      <!DOCTYPE html>
      <html>
      <head>
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, initial-scale=1">
          <title>Uploader</title>
      </head>
      <body>
          <form action="?" method="post" enctype="multipart/form-data">
              <br><br>
              <div>selecione a imagem 1</div>
              <input type="file" name="foto1" accept="image/*">
              <br><br>
              <input type="text" name="nome_imagem1">
              
              <br><br>
              <input type="file" name="foto2" accept="image/*">
              <br><br>
              <input type="text" name="nome_imagem2">
              
              <br><br>

              <input type="file" name="foto3" accept="image/*">
              <br><br>
              <input type="text" name="nome_imagem3">
              
              <br><br>
              <input type="submit" value="Enviar">
              <br><br>
          </form>
      <?php
      if ($_SERVER['REQUEST_METHOD'] == 'POST')
      {
          vardump ($_FILES);
      }
      ?>
      </body>
      </html>
       
       
       
    • Por belann
      Olá!
       
      Estou usando o nextjs versão 15.2.3 e criei uma navbar que quando é carregado o programa aparece com a home, mas na hora de clicar na página produtos desaparece a navbar.
      A navbar esta sendo chamada no layout.tsx estou usando typescript
      e fica dessa forma
      <div>           <Navbar/>             <main>{children}</main>             </div>  
    • Por ILR master
      Fala pessoal, tudo bem?
       
      Eu tenho o seguinte código:
       
      <script>
         $(function(){
      var jElement = $('.fixar_banner');
      $(window).scroll(function(){
          if ( $(this).scrollTop() > 120 ){
              jElement.css({
                  'position':'fixed',
                  'top':'10px'
              });
          }else{
              jElement.css({
                  'position':'relative',
                  'top':'auto'
              });
          }
      });
      });
      </script>
       
      Porém, eu quero que a div fique fixa até que outro elemento apareça na tela, tipo o rodapé da página por exemplo. É mais ou menos como a página de notícia do uol.
      https://noticias.uol.com.br/internacional/ultimas-noticias/2025/01/19/sonho-americano-brasileiros-moram-em-carro-e-buscam-comida-no-lixo-nos-eua.htm
       
      Espero ter sido claro.
       
      Obrigado :)
       
×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.