繁体   English   中英

组件中的 useState

[英]useState in a component

我在 function 中有一个 useState,我需要在同一组件中的 function 之外的 const 内读取 state。

不要使用 Redux 项目。

一些帮助?

您可以使用 props 在功能组件之间共享 state 变量值。

例如:

// Example1 Functional Compoent.
const Example1 = () => {
 const [stateData, setStateData] = useState<any>('Example Value');
 return (
  <>
   <Example2 [stateData]={stateData} />
  </>
 );
}

// Example2 Functional Compoent.
const Example2 = (props: any) => {
 console.log(props.stateData); // you will get the stateData from Example here.
 return (
  <>
   <p> { props.stateData } </p>
  </>
 );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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