js App the on put for component from variable get to How

huangapple go评论74阅读模式
英文:

How to get variable from component for put on the App.js

问题

以下是您要翻译的内容:

"even by searching on the internet I did not find, or in all that I did not understand.
My problem: I would like the "inputVal" variable found in the "InputField.js" component to be found where there is "!!HERE!!" in the "App.js" component (on the fetch)
please help me
thank you for reading my message!"

英文:

even by searching on the internet I did not find, or in all that I did not understand.
My problem: I would like the "inputVal" variable found in the "InputField.js" component to be found where there is "!!HERE!!" in the "App.js" component(on the fetch)
please help me
thank you for reading my message!

export default function InputField() {
  
  function handleSubmit(e) {
    // Prevent the browser from reloading the page
    e.preventDefault();

    // Read the form data
    const form = e.target;
    const inputVal = form.myInput.value;

    console.log(inputVal);
  }

  return (
    <form method="post" onSubmit={handleSubmit}>
      <input name="myInput" id="adress-field" placeholder="Enter adress" autoComplete="on" />
      <button type="submit" id="adress-button">Send</button>
    </form>
  );
}
import './App.css';
import AccountNumber from "./components/AccountNumber";
import InputField from "./components/InputField";
import { useEffect, useState } from "react"

function App() {

  //token fetch
  const [tockens, setTockens] = useState([])
  const [loading, setLoading] = useState(false)
  useEffect(() => {
    setLoading(true)
    fetch("https://api.multiversx.com/accounts/!!HERE!!/tokens")
      .then(response => response.json())
      .then(json => setTockens(json))
      .finally(() => {
        setLoading(false)
      })
      console.log(tockens); 
  }, [])


  function round(nr, ten) { // arondi un chiffre.
    return Math.round(nr * ten) / ten;
}

function numberWithSpaces(nr) { // formate un chiffre(x xxx xxx).
	return nr.toString().replace(/\B(?=(\d{3})+(?!\d))/g, " ");
}



  return (
    <content className="content">
        <div className="up-side">
            <div className="account-number-box">
                <p id="p-account-number">Total number of accounts</p>
                <p id="account-number"><AccountNumber/></p>
            </div>
            <div className="adress-search">
                {InputField()}
            </div>
            <p>{window.inputVal}</p>
        </div>
        <div className="down-side">
            <table className="Token-section-output">
            

              {loading ? (
                <div>Loading...</div>
              ) : (
                <>
                  <h1>Tockens</h1>
                  <table className='Token-section-output' border={0}>
                    <tr className='token-row-type'>
                      <th className='token-column'>Name</th>
                      <th className='center-column'>Price</th>
                      <th>Hold</th>
                    </tr>
                    <tr className="space20"/>

                    
                    {tockens.map(tocken => (
                      <tr className='token-row' key={tocken.id}>
                        <td className='token-column'>
                        <img className="img-Tockens" src = {tocken?.assets?.pngUrl ?? "img/Question.png"} /> 
                          <p>{tocken.name}</p> 
                        </td>

                        <td className='center-column'> <p>${round(tocken.price, 10000000)}</p> </td>

                        <td> 
                          <p>{round(tocken.balance / Math.pow(10, tocken.decimals), 10000000)}</p> 
                          <p className='token-hold'>${round(tocken.valueUsd, 10000000)}</p>
                        </td>
                      </tr>
                    ))}

                  </table>
                </>
              )}


            </table>
        </div>   
    </content>
  );
}

export default App;

I not very good in react and i mak search on internet

答案1

得分: 0

你想要扩展你的 InputField 组件,以接受一个可以由你的应用程序传递的回调函数:

export default function InputField({ onSubmit }) {
  
  function handleSubmit(e) {
    // 防止浏览器重新加载页面
    e.preventDefault();

    // 读取表单数据
    const form = e.target;
    const inputVal = form.myInput.value;

    console.log(inputVal);
    onSubmit(inputVal)
  }

  ...
}

并且在你的应用程序中,你需要将该回调传递给你的组件:

<div className="adress-search">
  <InputField onSubmit={handleSearchSubmit} />
</div>

注意:组件不是通过像函数一样调用来消耗的。

在你的应用逻辑中,你需要另一个状态来保存你的搜索值:

...
const [searchValue, setSearchValue] = useState(null);

const handleSearchSubmit = (val) => {
  setSearchValue(val);
}

useEffect(() => {
    setLoading(true)
    fetch(`https://api.multiversx.com/accounts/${searchValue}/tokens`)
      .then(response => response.json())
      .then(json => setTockens(json))
      .finally(() => {
        setLoading(false)
      });
    console.log(tockens); 
}, [searchValue])
...
英文:

You want to extend your InputField component to accept a callback function, that can be passed by your app:

export default function InputField({onSubmit}) {
  
  function handleSubmit(e) {
    // Prevent the browser from reloading the page
    e.preventDefault();

    // Read the form data
    const form = e.target;
    const inputVal = form.myInput.value;

    console.log(inputVal);
    onSubmit(inputVal)
  }

  ...
}

And in your App you need to pass that callback to your component:

&lt;div className=&quot;adress-search&quot;&gt;
  &lt;InputField onSubmit={handleSearchSubmit} /&gt;
&lt;/div&gt;

Note: Components are not consumed by calling them like functions.

In your App logic, you'll need another state to hold your search value:

...
const [searchValue, setSearchValue] = useState(null);

const handleSearchSubmit = (val) =&gt; {
  setSearchValue(val);
}

useEffect(() =&gt; {
    setLoading(true)
    fetch(`https://api.multiversx.com/accounts/${searchValue}/tokens`)
      .then(response =&gt; response.json())
      .then(json =&gt; setTockens(json))
      .finally(() =&gt; {
        setLoading(false)
      });
    console.log(tockens); 
}, [searchValue])
...

huangapple
  • 本文由 发表于 2023年6月2日 04:01:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76385320.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定