【问题标题】:how to set the input text in react by taking it from from the url?如何通过从 url 中获取输入文本来设置输入文本?
【发布时间】:2022-02-14 14:06:26
【问题描述】:

我正在尝试输入一个位置作为文本输入 我想要二维码显示打击和位置是我们在输入字段中输入的动态输入 https://google.com?location={location}?

如何设置上面的 url 并将位置作为输入?出现在二维码中

所以输入将是来自 url 的位置,可以是任何位置,并且 qr 代码应该显示

import React, { useState } from 'react';
import QRCode from 'qrcode.react';

function App() {

  const [inputText, setInputText] = useState('');
  const [qrCodeText, setQRCodeText] = useState('');

  // generate QR code
  const generateQRCode = () => {
    setQRCodeText(inputText);
  }

  
  return (
    <div className="App">
      <h3>Generate and download a QR code image in React Omneo</h3>
      <div className="qr-input">
        <input
          type="text"
          placeholder="Enter input"
          value={inputText}
          onChange={e => setInputText(e.target.value)}
        />
        <input
          type="button"
          value="Generate"
          onClick={generateQRCode}
        />
      </div>
      <QRCode
        id="qrCodeEl"
        size={150}
        value={qrCodeText}
      />
      
    </div>
  );
}

export default App;

【问题讨论】:

    标签: javascript arrays reactjs next.js


    【解决方案1】:
    //add to the top
    import { useEffect } from 'react'
    
    //add above return
    useEffect(() => {
        setInputText(window.location.href);
      })
    

    【讨论】:

    • 我已经尝试过在输入中获取 url,但问题是我想从 url 中获取位置并在输入中使用它并在 qr @user1898662 中显示 url
    【解决方案2】:

    如果 URL 只有一个参数(位置),您可以拆分并获取其余参数。如果有更多参数,你可以用'&'然后位置来分割

    useEffect(() => {
        setInputText(window.location.href.split("location=")[1]);
    }, [])

    【讨论】:

    • 使用 useffect 设置 url,我已经尝试过,但我只得到了我传递的 url,但问题是我想从 url 中获取位置并在输入中使用它并显示 url qr @Raven
    • 所以输入将是来自 url 的位置,可以是任何位置,并且二维码应该显示
    • 理论上这应该可以工作,因为当 window.location.href 更改时它会再次设置但它不起作用你也可以使用来自反应路由器 useEffect(() => { if(window.location .href.includes('location') setInputText(window.location.href.split("location=")[1]); }, [window.location.href])
    猜你喜欢
    • 2019-02-13
    • 1970-01-01
    • 2015-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多