[英]How to define local variable in another react file
I have to use Abc variable from a.tsx to another b.tsx file.我必须使用从 a.tsx 到另一个 b.tsx 文件的 Abc 变量。 How can I access that Abc variable in another .tsx file?如何在另一个 .tsx 文件中访问该 Abc 变量?
Current a.tsx:当前 a.tsx:
export const ProfilePicEditor = (props: ProfilePicEditorProps) => {
const [Abc, setAbc] = useState(
'some string'
)
I tried doing 'export {Abc}' in my a.tsx file and importing it into b.tsx file as 'Import {Abc} from 'a.tsx'.我尝试在我的 a.tsx 文件中执行“export {Abc}”并将其作为“Import {Abc} from 'a.tsx”导入到 b.tsx 文件中。 But it didn't worked out.但它没有成功。 Any possible reasons?有什么可能的原因吗?
What is the relationship between the two components? 这两个部分之间是什么关系? Parent/child? 父母/孩子? Siblings? 兄弟姐妹?
React generally expects you (and is designed) to pass data as part of the state via the props. React通常期望您(并被设计为)通过道具将数据作为状态的一部分传递。
So if you want to pass data between components and you are not using Redux or a similar library, you need to pass the data in the constructor as a prop and have your constructor extract it. 因此,如果您要在组件之间传递数据,并且不使用Redux或类似的库,则需要将数据作为道具传递给构造函数,并让构造函数提取它。
You should pass the variable as a prop to the child component, if the parent is who wants to accede to the variable you can use a ref 您应该将变量作为道具传递给子组件,如果父母希望加入该变量,则可以使用引用
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.ChildComponent = React.createRef();
}
render() {
return <ChildComponent ref={this.ChildComponent} />;
}
}
you can use it like this: 您可以像这样使用它:
const currentChildComponent = this.currentChildComponent.current; const currentChildComponent = this.currentChildComponent.current;
提升状态或使用状态管理库,例如Redux或MobX。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.