[英]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.