首页 > 解决方案 > 为什么反引号在 React 中返回未定义

问题描述

所以我正在为一个站点创建一个用户搜索功能,但是每当我在 React 中传递一个反引号时,它就会返回,undefined我尝试将它转换为一个字符串,没有任何变化。

import React, { useRef } from'react';
import { Link } from "react-router-dom";
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faSearch } from '@fortawesome/free-solid-svg-icons'

function SearchBox() {
  const searchRef = useRef('');
  var query = `search/${searchRef.current.value}`;
  return (
    <form className="searchContainer" method="post">
      <h1>WAFFLES :D</h1>
      <div className="searchBox">
        <input ref={searchRef} type="text"/>
        <Link className="searchGlass" to={query}><FontAwesomeIcon icon={faSearch}/></Link>
      </div>
    </form>
  );
}

export default SearchBox;

标签: javascriptreactjsreact-routerreact-router-dom

解决方案


ref 将被更新为 HTMLInputElement,但看起来您的意图是让输入的在 ref 更改时更新它。

  • 您需要使用useState才能在值更改时重新渲染;useRef不会to={query}根据需要重新渲染和更新
function SearchBox() {
  const [query, setQuery] = useState('');
  const linkTo = `search/${query}`;

  function handleChange(event) {
    setQuery(event.target.value);
  }

  return (
    <form className="searchContainer" method="post">
      <h1>WAFFLES :D</h1>
      <div className="searchBox">
        <input onChange={handleChange} type="text" value={query} />
        <Link className="searchGlass" to={linkTo}>
          <FontAwesomeIcon icon={faSearch} />
        </Link>
      </div>
    </form>
  );
}

推荐阅读