简体   繁体   中英

Passing Props With Input - React

Within a child component I have state to store input.

My goal is to pass the input state to the parent component.

    //Child component 

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

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

I tried creating a function to be called on input within the parent function but I cannot seem to get the value "input" passed. What is the correct way to do this? Thanks!

You can move the state to the parent component. Then pass the props from the child to the parent.

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)} />
    )
}

you were approaching correctly. You can pass a function to get the data from the child to the parent. Check this example:

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>
    </>
  );
};

The parent App is retrieving the text from the child Component passing the function getInput . You only have to decide with event you want to detonate. Of course, this is with input not with TextField. I think that you are using TextField from React Material UI, if that's the case you may check the docs to know how to trigger an event.

I finally figured this out.

// 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM