@nathan111777

Как бы выглядел такой JS код в React?

Как бы выглядел такой JS код в React?

Что б при нажатии на кнопку где-то встороне появилось окошко.

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {font-family: Arial, Helvetica, sans-serif;}


.modal {
  display: none; 
  position: fixed; 
  z-index: 1; 
  padding-top: 100px; 
  left: 0;
  top: 0;
  width: 100%; 
  height: 100%; 
  overflow: auto; 
  background-color: rgb(0,0,0); 
  background-color: rgba(0,0,0,0.4); 
}

/* Modal Content */
.modal-content {
  background-color: #fefefe;
  margin: auto;
  padding: 20px;
  border: 1px solid #888;
  width: 80%;
}

/* The Close Button */
.close {
  color: #aaaaaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: #000;
  text-decoration: none;
  cursor: pointer;
}
</style>
</head>
<body>

<h2>Modal Example</h2>

<!-- Trigger/Open The Modal -->
<button id="myBtn">Open Modal</button>

<!-- The Modal -->
<div id="myModal" class="modal">

  <!-- Modal content -->
  <div class="modal-content">
    <span class="close">&times;</span>
    <p>Some text in the Modal..</p>
  </div>

</div>

<script>

var modal = document.getElementById("myModal");
var btn = document.getElementById("myBtn");
var span = document.getElementsByClassName("close")[0];

btn.onclick = function() {
  modal.style.display = "block";
}

span.onclick = function() {
  modal.style.display = "none";
}

window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}
</script>

</body>
</html>
  • Вопрос задан
  • 444 просмотра
Решения вопроса 2
RomReed
@RomReed
JavaScript, Flutter, ReactNative, Redux, Firebase
Ответ написан
Комментировать
0xD34F
@0xD34F Куратор тега React
const Modal = (props) => {
  const onClick = e => {
    if (e.target.classList.contains('close') || !e.target.closest('.modal-content')) {
      props.close();
    }
  }

  return (
    <div className="modal" onClick={onClick}>
      <div className="modal-content">
        <span className="close">&times;</span>
        {props.children}
      </div>
    </div>
  );
};

const App = () => {
  const [ opened, setOpened ] = React.useState(false);

  const open = () => setOpened(true);
  const close = () => setOpened(false);

  return (
    <div>
      <h2>Modal Example</h2>
      <button onClick={open}>Open Modal</button>
      {opened && <Modal close={close}>hello, world!!</Modal>}
    </div>
  );
}

https://jsfiddle.net/zuscf0wo/
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы