英文:
how can i pass data from a function to another file in react with calling that component or use props
问题
filename - Header.jsx
import { useEffect, useState } from 'react';
import { getValue } from './Input';
import TextField from '@mui/material/TextField';
export const Header = () => {
const [search, setSearch] = useState('');
useEffect(() => {
getValue(search, continents);
}, [search, continents]);
return (
<TextField id="outlined-basic" label="Outlined" variant="outlined" onChange={(e) => setSearch(e.target.value)} />
);
}
filename - CountryData.jsx
let setVal = [];
export const getValue = (...val) => {
setVal = val;
return setVal;
};
export const CountryData = () => {
const [searchVal, setSearchVal] = useState('');
useEffect(() => {
setSearchVal(setVal[0]);
}, [setVal, getValue]);
return null; // This component doesn't render anything, as you want to separate the rendering.
}
i want to pass the data from input field from Header.jsx file to CountryData.jsx file without calling the component because i want to separate the both header and CountryData element separate in html. Maybe i am wrong in doing something. Please help and Thank you.
英文:
filename - Header.jsx
import { useEffect, useState } from 'react'
import { getValue } from './Input'
import TextField from '@mui/material/TextField';
export const Header = () => {
const [search, setSearch] = useState('')
useEffect(()=>{
getValue(search,continents)
},[search,continents])
<TextField id="outlined-basic" label="Outlined" variant="outlined" onChange={(e) => setSearch(e.target.value)} />`
filename - CountryData.jsx
let setVal = [];
export const getValue = (...val) => {
setVal = val;
return setVal;
};
export const CountryData = () => {
const [searchVal, setSearchVal] = useState('')
useEffect(() => {
setSearchVal(setVal[0]);
}, [setVal,getValue]);
}
i want to pass the data from input field from Header.jsx file to CountryData.jsx file without calling the component because i want to seperate the both header and CountryData element seperate in html. Maybe i am wrong in doing something. Please help and Thankyou
答案1
得分: 0
你可以使用useContext。将其想象成你的应用程序的存储库。在你的 Header 组件中,你可以将数据/值设置到该存储库中。然后,在 CountryData 组件中,你可以从存储库中检索数据以供使用。
英文:
You can use useContext. Imagine it as a store for your app. In your Header component, you can set the data/value to that store. Then, in the CountryData component, you can retrieve the data from the store to use.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论