我可以在 React hooks(函数组件)中的另一个组件中使用一个组件内的值吗?
component1.js
const component1= (props) => {
const [**selectedCountry**, setSelectedCountry] = useState();
<Dropdown onSelect={eventKey => {
const { code } = countries.find(({ code }) => eventKey === code);
setSelectedCountry(eventKey);
setToggleContents(<><FlagIcon code={code} /> </>);
}}
>
<Dropdown.Menu>
{countries.map(({ code, title }) => (
<Dropdown.Item key={code} eventKey={code}><FlagIcon code={code} /> {title}</Dropdown.Item>
))}
</Dropdown.Menu>
</Dropdown>
.
.
}
该组件内的变量。根据下拉变化变成setSelectedCountry。我如何在 component2.js 中获取这个值(我需要 selectedCountry 值)?
export default function component2() {
useEffect(() => {
postService.getLanguage(**HERE VALUE**).then((response)=>{
setData(response.data);
},
(error) => {
console.log(error);
}
);
}, []);
***I will take this value as a parameter and evaluate it in get (selectedCountry)How can I ***
}
component1.js
const component1= (props) => {
const [**selectedCountry**, setSelectedCountry] = useState();
<Dropdown onSelect={eventKey => {
const { code } = countries.find(({ code }) => eventKey === code);
setSelectedCountry(eventKey);
setToggleContents(<><FlagIcon code={code} /> </>);
}}
>
<Dropdown.Menu>
{countries.map(({ code, title }) => (
<Dropdown.Item key={code} eventKey={code}><FlagIcon code={code} /> {title}</Dropdown.Item>
))}
</Dropdown.Menu>
</Dropdown>
.
.
}
a variable within this component. It becomes setSelectedCountry according to the dropdown change. how can i get this value in component2.js (i need selectedCountry value) ?
export default function component2() {
useEffect(() => {
postService.getLanguage(**HERE VALUE**).then((response)=>{
setData(response.data);
},
(error) => {
console.log(error);
}
);
}, []);
***I will take this value as a parameter and evaluate it in get (selectedCountry)How can I ***
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,您可以在此处使用 createContext 和 useContext 函数: https://reactjs.org/docs/context.html
或者,您可以使用 Redux 来帮助您管理多个组件使用的状态。
Yes, you can use createContext and useContext function here: https://reactjs.org/docs/context.html
Alternatively you can use Redux to help you manage states used by multiple components.