我在构建 React 搜索栏时遇到了麻烦。
我无法从 input
字段获取输入文本。
演示:https://codesandbox.io/s/amazing-pare-gds8m 我的代码:
const App = () => {
const [data,setData] = useState(null)
const [print, setPrint] = useState(false)
function getData(val){
console.log(val.target.value)
setData(val.target.value);
setPrint(false)
//assigning inputed text value and return from this function
let returnValue = (val.target.value)
return (val.target.value)
}
console.log(returnValue) // I'm getting error here: returnValue not defined
useEffect(() => {
const fecthPosts = async () => {
let initial_url = `http://localhost:4000/search`
let url = initial_url + "?text=" + returnValue; //can't be used
const res = await fetch(`${url}`);
//Further Process.
fecthPosts();
},[]);
return(
<div className="App">
{
print?
<h2>{data}</h2> //displaying the entered data in webpage
:null
}
<input type="text" onChange={getData} />
<button onClick={() => setPrint(true)}>go</button>
</div>
)
}
};
export default App;
我只是从 inputed
函数返回 getData()
文本。像这样:
function(){
const var1 = "apple"
return var1;
}
console.log(var1) //works perfectly fine here but not in React :(
有什么想法可以使这成为可能吗?
请帮帮我
答案 0 :(得分:0)
您对作用域有一个非常根本的误解(您使用的变量是在函数中定义的),但实际上您已经在使用 setData 做您需要做的事情。
import React, { useState } from "react";
const App = () => {
const [data, setData] = useState(null);
const [print, setPrint] = useState(false);
const [inputText, setInputText] = useState({
text: "" //Initializing the text
});
function getData(val) {
console.log("val.target.value", val.target.value);
setData(val.target.value);
setPrint(false);
}
console.log("data", data)
// useEffect(() => {
// const fecthPosts = async () => {
// let initial_url = `http://localhost:4000/search` // My Api here
// let url = initial_url + "?text=" + returnValue;
// const res = await fetch(`${url}`);
// //Further Process.
// fecthPosts();
// },[page]);
return (
<>
<div className="App">
{print ? (
<h2>{data}</h2> //displaying the entered data in webpage
) : null}
<input type="text" value={data} onChange={getData} />
<button onClick={() => setPrint(true)}>go</button>
</div>
</>
);
};
export default App;
如您所见,当您使用输入字段值作为参数调用 setData() 时,状态变量“data”将使用输入字段中的值更新。