当我在react中使用iframe渲染html文档时获取用户输入值信息

问题描述 投票:0回答:1

我在 html 文档中有一个从 API 获得的输入标签。

<input placeholder="Enter Name" type="text"/>

我正在使用 iframe srcDoc 在 .js 组件中的 React 中渲染它, 当用户在输入字段上输入任何内容时,我想在 React 组件中捕获该信息,但我不确定如何捕获我使用 iframe 渲染的 html 文档一部分的输入值。

有人可以帮忙解决这个问题或有任何建议吗?

javascript html reactjs react-native iframe
1个回答
0
投票

我使用了一个 p 标签来显示输入值。您可以根据您的要求进行定制。请尝试下面更新的代码:-

import React, { useState } from 'react';

function App() {
  const [inputValue, setInputValue] = useState('');

  const handleMessage = (event:any) => {
    if (event.origin !== window.location.origin) return; // Check origin for security

    const { type, payload } = event.data;
    if (type === 'inputValue') {
      setInputValue(payload);
    }
  };

  window.addEventListener('message', handleMessage);

  return (
    <div>
      <p>Input value from iframe: {inputValue}</p>
      <iframe title="iframe" srcDoc={`
          <html>
            <head>
              <title>IFrame Content</title>
            </head>
            <body>
              <input placeholder="Enter Name" type="text" onInput="parent.postMessage({type: 'inputValue', payload: this.value}, '*');" />
            </body>
          </html>
        `} />
    </div>
  );
}

export default App;

让我知道它是否适合您。

© www.soinside.com 2019 - 2024. All rights reserved.