【问题标题】:Access a variable in react-typescript访问 react-typescript 中的变量
【发布时间】:2021-05-24 15:05:50
【问题描述】:

我正在学习 react-typescript,

代码-

import {phones} from "../../get_phone";

interface IProps {
    phone: phones,
}

const Query1: React.FC <IProps> = ({phone}) => 
{
    console.log(phone)    
    const [model, setmodel] = useState(phone);
    console.log(model);
}

是否可以从其他组件以及其他打字稿文件中访问model 变量?

谢谢

【问题讨论】:

  • useState 它是一个渲染钩子,如果状态改变,那么渲染就会改变......但是如果你想要一个全局变量,我建议你使用上下文变量(useContext)你可以阅读它-> reactjs.org/docs/hooks-reference.html

标签: reactjs typescript react-native


【解决方案1】:

你可以尝试使用Custom Hooks:

useQuery.ts

const useQuery: React.FC<IProps> = ({ phone }) => {
  const [model, setModel] = useState(phone);
  return { model, setModel }
};

otherComponent.tsx

const OtherComponent: React.FC = () => {
  const { model, setModel } = useQuery({ phone });

  // can use `model` here
  return <div>something</div>;
};

【讨论】:

    【解决方案2】:

    model 的值只能在 react 的渲染周期内访问。如果您想将它传递给其他组件,这就是 props 的用途。如果它是深度嵌套的组件,您可以使用Context Api

    通常models 的值在没有真正肮脏的 hack 的情况下无法在 react 的渲染周期之外访问。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-17
      • 1970-01-01
      • 2016-07-28
      • 1970-01-01
      • 2021-09-22
      • 2018-08-21
      • 1970-01-01
      • 2012-10-04
      相关资源
      最近更新 更多