передать данные от компонента к компоненту react
У меня есть код на react, который использует два независимых компонента. При нажатии на кнопку в первом компоненте я скрываю текущий компонент и отображаю другой компонент. Но также я хочу передавать некоторые значения из первого компонента (из INPUTS) во второй компонент. Подскажите, пожалуйста, как я могу это сделать? Вот код:
App.js
import React from 'react';
import { useState } from 'react';
import { FirstSection} from './components/FirstSection';
import { SecondSection} from './components/SecondSection';
function App() {
const [checkSection, setSection] = useState(false);
const showSecondSection= () => setSection(true);
return (
<div className="App">
{checkSection ? <SecondSection /> : <FirstSection onClick={showSecondSection} />}
</div>
);
}
export default App;
FirstSection.jsx
export function FirstSection({onClick}) {
return(
<>
<input type="text" value="{input1}" />
<input type="text" value="{input2}" />
<button onClick={onClick}>Continue</button>
</>
)
}
SecondSection.jsx
export function SecondSection() {
return(
<>
<p>{input1}, {input2}</p> <== Сюда я хочу передать данные из первого компонента
</>
)
}
Ответы (1 шт):
Автор решения: Randall
→ Ссылка
import React from 'react';
import { useState } from 'react';
import { FirstSection} from './components/FirstSection';
import { SecondSection} from './components/SecondSection';
function App() {
const [checkSection, setSection] = useState(false);
const showSecondSection= () => setSection(true);
const [firstInput, setFirstInput] = useState("");
const [secondInput, setSecondInput] = useState("");
return (
<div className="App">
{checkSection ?
<SecondSection
firstInput={firstInput}
secondInput={secondInput}
/> :
<FirstSection
firstInput={firstInput}
secondInput={secondInput}
setFirstInput={setFirstInput}
setSecondInput={setSecondInput}
onClick={showSecondSection}
/>
}
</div>
);
}
export default App;
Компонент FirstSection
export function FirstSection({onClick, firstInput, setFirstInput, secondInput, setSecondInput }) {
return(
<>
<input type="text" value={firstInput} onChange={e => setFirstInput(e.target.value)}/>
<input type="text" value={secondInput} onChange={e => setSecondInput(e.target.value)} />
<button onClick={onClick}>Continue</button>
</>
)
}
Компонент SecondSection
export function SecondSection({ firstInput, secondInput }) {
return(
<>
<p>{firstInput}, {secondInput}</p>
</>
)
}