[英]How to return the value from function in React?
我想從函數組件返回輸入的文本。
代碼:
演示: https : //codesandbox.io/s/pedantic-tesla-nlx4t
import React from "react";
function App() {
const inputRef = React.useRef();
const handleSubmit = (event) => {
event.preventDefault();
// console.log("Your Text:" + inputRef.current.value);
return inputRef.current.value
};
console.log(inputRef.current.value) // Not getting the value.
useEffect(() => {
// I've to use master here to send request to my API..
const res = fetch(`http://localhost:4000/search?text=${inputRef.current.value}`)
const result = res.json();
},[])
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" ref={inputRef} />
</label>
<input type="submit" value="Submit" />
</form>
);
};
export default App;
我該怎么做呢?? 我必須在useEffect
使用它來從它獲取數據。 對此有什么想法嗎??
首先 master 不是全局的,而是僅在 handleSubmit 函數中是本地的,其次您可以使用 useState
https://reactjs.org/docs/forms.html
import React, { useEffect, useState } from "react"; function App() { const [inputRef, setRefVal] = useState(""); const [resultFromFetch, setResult] = useState(""); const handleSubmit = (event) => { event.preventDefault(); // console.log("Your Text:" + inputRef.current.value); }; function handleChange(event) { setRefVal(event.target.value); console.log(inputRef); } console.log(inputRef); // Not getting the value. useEffect(() => { // I've to use master here to send request to my API.. // const res = fetch( // `http://localhost:4000/search?text=${inputRef}` // ); setResult(/*here result from your request*/''); }, []); return ( <form onSubmit={handleSubmit}> <label> Name: <input type="text" value={inputRef} onChange={handleChange} /> </label> <input type="submit" value="Submit" /> </form> ); } export default App;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
import React, {useState} from 'react'
const App = () => {
const [inputVal, setInputVal] = useState("");
const handleSubmit = (event) => {
event.preventDefault();
fetch(`http://localhost:4000/search?text=${inputVal}`)
.then(response => response.json())
.then(data => console.log(data)) // your response data, do whatever you want
.catch((error) => console.error(error));
};
const handleChange = (event) => {
setInputVal((event.target.value), console.log(inputVal)); //state update is async
}
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" value={inputVal} onChange={handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
export default App;
嘿伙計,我認為很少有主題可以幫助您更多地了解問題所在。
我希望它會幫助你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.