使用用户输入反应更改 iframe src

React change iframe src with user input

我希望能够在 React 的帮助下更改 iframe src,但我不知道该从哪里开始,因为我是一般编码的新手。

我设法用 html 和 js 构建了我想要的东西,但是当我将代码转储到反应项目中时它不起作用。

编辑:我尝试使用在线转换器将 html 和 js 转换为 jsx,但没有成功。

请查看下面的代码是如何工作的,请指出正确的方向。

<input type="number" id="book"></input>
<input type="number" id="page"></input>
<button type="button" onClick="goBook();">Submit</button>
<iframe
    id="myBook"
    src="https://www.google.com"
    height="720"
    width="1280"
    frameborder="0"
    scrolling="no"
    allowfullscreen="true">
</iframe>

<script>
    function goBook(){
  document.getElementById("myBook").src = "https://www.example.com/b="+document.getElementById("book").value+"&p="+document.getElementById("page").value;
}
</script>

请有人帮助我!

您需要从 create-react-app 开始。

获得基本的 React 应用程序模板后,转到 App.js 并编写以下代码:

import "./styles.css";
import { useState } from "react";

export default function App() {
  const [srcURL, setsrcURL] = useState("https://www.google.com");
  const [book, setBook] = useState(null);
  const [page, setPage] = useState(null);

  const handleSubmit = () => {
    if (book && page) {
      setsrcURL(`${"https://www.google.com"}/b=${book}&p=${page}`);
    }
  };

  return (
    <div className="App">
      <input
        type="number"
        name="book"
        placeholder="Book Number"
        onChange={(e) => setBook(e.target.value)}
      />
      <input
        type="number"
        placeholder="Page Number"
        name="page"
        onChange={(e) => setPage(e.target.value)}
      />
      <button type="button" onClick={handleSubmit}>
        Submit
      </button>
      <iframe
        name="myBook"
        src={srcURL}
        height="720"
        width="1280"
        frameBorder="0"
        scrolling="no"
        allowFullScreen={true}
      />
    </div>
  );
}

我的回答就这样被删了。我只是复制粘贴到这里。

import { useRef, useState } from "react";

export default function App() {
  const googleUrl = "https://www.google.com";

  const refBook = useRef(null);
  const refPage = useRef(null);
  const refIframe = useRef(null);
  const [iframSrc, setIframeUrl] = useState(googleUrl);

  const goBook = () => {
    setIframeUrl(
      `${googleUrl}/b=${refBook.current.value}&p=${refPage.current.value}`
    );
  };

  return (
    <div className="App">
      <input type="number" ref={refBook}></input>
      <input type="number" ref={refPage}></input>
      <button type="button" onClick={goBook}>
        Submit
      </button>
      <iframe
        title="myBook"
        src={iframSrc}
        height="720"
        width="1280"
        frameBorder="0"
        scrolling="no"
        allowFullScreen={true}
        ref={refIframe}
      ></iframe>
    </div>
  );
}