Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何在另一个react文件中定义局部变量_Reactjs_Typescript_Scope_React Hooks - Fatal编程技术网

Reactjs 如何在另一个react文件中定义局部变量

Reactjs 如何在另一个react文件中定义局部变量,reactjs,typescript,scope,react-hooks,Reactjs,Typescript,Scope,React Hooks,我必须使用从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}从a.tsx”导入到

我必须使用从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}从a.tsx”导入到b.tsx文件中。但是没有成功。有什么可能的原因吗?

这两个组件之间的关系是什么?父母/子女?兄弟姐妹

React通常需要您,并设计为通过props作为状态的一部分传递数据


因此,如果您希望在组件之间传递数据,并且您没有使用Redux或类似的库,则需要将构造函数中的数据作为道具传递,并让构造函数将其提取。

您应该将变量作为道具传递给子组件,如果父组件希望加入变量,则可以使用ref

class ParentComponent extends React.Component {
  constructor(props) {
    super(props);
    this.ChildComponent = React.createRef();
  }
  render() {
    return <ChildComponent ref={this.ChildComponent} />;
  }
}
您可以这样使用它:


const currentChildComponent=this.currentChildComponent.current

它的可能副本看起来像是您正在尝试创建一个定制的react钩子,也许可以看看本文。它有一个很好的工作示例,提取其中一个的好步骤是:我可以在同一个文件中使用钩子,但当我尝试在b.tsx中使用导入函数时,它会给我一个错误:找不到名称Abc或Abc在ProfilePicEditor上不存在。这两个组件之间的关系是父/子组件。然后,您可以使用父组件中的回调从子组件传回数据。在父级上创建一个函数,将数据作为参数并从子级调用它。这里有一个例子: