[英]Access a variable in 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);
}
是否可以從其他組件以及其他 typescript 文件訪問model
變量?
謝謝
您可以嘗試使用 自定義掛鈎:
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>;
};
model
的值只能在反應的渲染周期內訪問。 如果你想將它傳遞給其他組件,那就是props的用途。 如果它是深度嵌套的組件,您可以為此使用Context Api
。
一般來說,如果沒有真正骯臟的黑客攻擊, models
的值在 react 的渲染周期之外是無法訪問的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.