簡體   English   中英

如何在另一個反應文件中定義局部變量

[英]How to define local variable in another react file

我必須使用從 a.tsx 到另一個 b.tsx 文件的 Abc 變量。 如何在另一個 .tsx 文件中訪問該 Abc 變量?

當前 a.tsx:

export const ProfilePicEditor = (props: ProfilePicEditorProps) => {
    const [Abc, setAbc] = useState(
        'some string'
    )

我嘗試在我的 a.tsx 文件中執行“export {Abc}”並將其作為“Import {Abc} from 'a.tsx”導入到 b.tsx 文件中。 但它沒有成功。 有什么可能的原因嗎?

這兩個部分之間是什么關系? 父母/孩子? 兄弟姐妹?

React通常期望您(並被設計為)通過道具將數據作為狀態的一部分傳遞。

因此,如果您要在組件之間傳遞數據,並且不使用Redux或類似的庫,則需要將數據作為道具傳遞給構造函數,並讓構造函數提取它。

您應該將變量作為道具傳遞給子組件,如果父母希望加入該變量,則可以使用引用

class ParentComponent extends React.Component {
  constructor(props) {
    super(props);
    this.ChildComponent = React.createRef();
  }
  render() {
    return <ChildComponent ref={this.ChildComponent} />;
  }
}

您可以像這樣使用它:

const currentChildComponent = this.currentChildComponent.current;

提升狀態或使用狀態管理庫,例如Redux或MobX。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM