简体   繁体   English

如何在另一个反应文件中定义局部变量

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

相关问题 反应将局部变量发送到另一个文件 - React sending local variable to another file 如何从另一个文件中导出钩子局部变量以及反应中的组件? - how to export a hook local variable from another file along with the component in react? 无法从其他文件定义导入的 object,存储在 state 中并将其传播到 React 中的另一个变量中 - Unable to define an imported object from a different file , store in a state and spread it in another variable in React 如何从组件中获取变量并在另一个组件或文件中使用它 React - How to take variable from component and use it in another component or file React React - 如何将变量从一个文件获取到另一个文件 - React - how to get variable from one file to another 如何从另一个js文件访问react组件中定义的变量? - How to access a variable defined in a react component from another js file? 如何在反应中从另一个文件设置状态变量 - How to set state a variable from another file in react 如何在反应中将函数变量从一个文件传递到另一个文件 - how to pass function variable from one file to another in react 如何将变量导出到另一个文件 React - How can I export a variable to another file React 在反应中将变量从一个文件导出到另一个文件 - Export variable from one file to another in react
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM