0

У меня в App() в return выводится форма из HandleInput(), там есть параметр input, мне его нужно передать в App() для подальшего взаимодействия.

Иными словами, чтобы можно было взаимодействовать в функции App() с полученными данными из инпута в функции HandleInput()

В функции App() нужно чтобы вместо "Animated text" был параметр input

index.jsx:

import React from "react";
import ReactDOM from "react-dom/client";
import { useState, useEffect } from 'react';

import "./index.css";

function HandleInput() {
    const [input, setInput] = useState("");

    const handleSubmit = (event) => {
        event.preventDefault();
    }

    return (
        <>
            <form onSubmit={handleSubmit}>
                <input
                    name="text"
                    value={input}
                    placeholder="Input text"
                    onChange={(e) => setInput(e.target.value)}
                />
                <br />
                
                <input 
                    type="submit"
                    value="Submit"
                />
            </form>

            <p>Output: {input}</p>
        </>
    )
}

function App() {
    const [text, setText] = useState("");
    const [counter, setCounter] = useState(0);

    const fullWord = "Animated text ";

    const word = Array.from(fullWord);

    const showTextWithTimeout = () => {
        if (counter >= 0 && counter < word.length-1) {
            setCounter((counter) => counter + 1);
        } 
        else {
            setCounter((counter) => counter = 0);
        }
    }

    useEffect(() => {
        setTimeout(() => {
            showTextWithTimeout();
            
            if (counter >= 0 && counter < word.length-1) {
                setText(text + word[counter]);
            }

            else if (counter === word.length-1) {
                setText("");
            }   
        
        }, 200);
    })

    return (
        <div className="container">
            <HandleInput />

            <p>{text}</p>
        </div>
    );
}

const root = ReactDOM.createRoot(document.querySelector("#root"));
root.render(<App />);

1 ответ 1

1

Вынеси в App состояние:

const [input, setInput] = useState("");

и когда будешь рендерить элемент HandleInput в App передавай состояние пропсами. Должно выглядеть что-то на подобии этого

App.js

const App = () => {
  const [input, setInput] = useState("");
  return (
    ...другие компоненты
    <HandleInput 
      input={input}
      setInput={setInput}
    />
    ...другие компоненты
  )
}

HandleInput.js

const HandleInput = ({ input, setInput }) => {
  return (
    <>
      ...другие компоненты
      <input
        name="text"
        value={input}
        placeholder="Input text"
        onChange={(e) => setInput(e.target.value)}
      />
      ...другие компоненты
    </>
  )
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.