javascript - 为什么反引号在 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;
解决方案
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>
);
}
推荐阅读
- php - Laravel 集合从每个函数中检索变量结果
- api - 如何区分 url 中的端点、路径、参数?
- python - 使用python将CSV文件中特定列中的“/”替换为“_”
- reactjs - TypeError:无法读取 React-hooks 中未定义的属性“toLowerCase”
- c++ - 检查给定的关系是否可传递,如果不是,则添加新的对以使其具有传递性
- react-native - 我正在尝试使用本机反应制作应用程序,并且我想实现底部导航栏
- python - 如何在pygame中创建跳跃动作
- html - 使用 CSS 变换比例时如何保持原始位置?
- python-3.x - 如何在 python 中打印文字字节?
- cursor - 如何检查光标(dbh)是否在python中用于sybase连接