簡體   English   中英

如何從 React 中的函數返回值?

[英]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;

嘿伙計,我認為很少有主題可以幫助您更多地了解問題所在。

  1. 受控組件與非受控組件。 https://itnext.io/controlled-vs-uncontrolled-components-in-react-5cd13b2075f9
  2. 反應鈎子。 https://reactjs.org/docs/hooks-intro.html
  3. 承諾/異步。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
  4. 獲取api。 https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

我希望它會幫助你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM