簡體   English   中英

通過輸入傳遞道具 - React

[英]Passing Props With Input - React

在子組件中,我有 state 來存儲輸入。

我的目標是將輸入 state 傳遞給父組件。

    //Child component 

    const [userInput, setUserInput] = useState("");

    <TextField value={input} onInput={e => setInput(e.target.value)} />

我嘗試創建一個 function 以在父級 function 中的輸入上調用,但我似乎無法獲得傳遞的值“輸入”。 這樣做的正確方法是什么? 謝謝!

您可以將 state 移動到父組件。 然后將道具從孩子傳遞給父母。

function Child({
    ...rest
}) {
    return <TextField {...rest} />
}
function Parent() {
    const [input, setInput] = useState(''); // '' is the initial state value
    return (
        <Child  value={value} onInput={e => setInput(e.target.value)} />
    )
}

你走對了。 您可以傳遞 function 以從子級獲取數據到父級。 檢查這個例子:

import { useState } from "react";
import "./styles.css";

export default function App() {
  const [text, setText] = useState("");

  const getInput = (t) => {
    console.log(t);
    setText(t);
  };

  return (
    <div className="App">
      <Component getInput={getInput} value={text} />
      <p>{text}</p>
    </div>
  );
}

const Component = ({ getInput, value }) => {
  return (
    <>
      <h1> Test </h1>
      <input type="text" value={value} onChange={(e) => getInput(e.target.value)}></input>
    </>
  );
};

App正在通過 function getInput從子Component檢索文本。 您只需要決定要引爆的事件。 當然,這是針對input而不是 TextField。 我認為您正在使用 React Material UI 中的 TextField,如果是這種情況,您可以查看文檔以了解如何觸發事件。

我終於想通了。

// This is in the parent component 

const [userInput, setUserInput] = useState("");

// Step 1: Create a function that handles setting the state 
const inputHandler = (userInput) => {
setUserInput(userInput);
}

<PhaseTwoTemplate onInput={inputHandler}  />
//Step 2: Add a function that calls the handler

...

// This is the child component PhaseTwoTemplete.js

const [input, setInput] = useState(""); 
// This second state holds the input data for use on child component
// It also is an easy way to hold the data for the parent function. 

 
<TextField 
onChange={e => setInput(e.target.value)}
value={input}  
onInput={onInputHandler} 
/>

// Step 3: Pass the user input to the parent
const onInputHandler = () => {
props.onInput(input);
}

暫無
暫無

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

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