[英]React Native:Why does the child component have access in a variable which is inside the useEffect in a parent component?
i have the following code.I can't understand why the "TestA" component has access to the "s" variable which is inside the useEffect in "Test" component.我有以下代码。我不明白为什么“TestA”组件可以访问“Test”组件的 useEffect 内部的“s”变量。
import React, {useEffect, useState} from 'react';
import {View, Text} from 'react-native';
const Test = ({children}) => {
const [init, setInit] = useState(0);
useEffect(() => {
setInit(1);
}, []);
useEffect(() => {
s = {
example: 'www',
};
}, []);
// console.log(s);
return init > 0 ? <View>{children}</View> : <Text>Noooo</Text>;
};
const TestA = () => {
console.log(s); -->why this has access inside the useEffects' variable "s"???
return (
<View>
<Text>Hello {s.example}</Text>
</View>
);
};
const App = () => {
return (
<>
<Test>
<TestA />
</Test>
</>
);
};
export default App;
I notice this happen only for ReactNative.In React something like that doesn't work.Is something that babel does in react native.Here is my package.json file:我注意到这种情况只发生在 ReactNative 中。在 React 中类似的东西不起作用。是 babel 在 react native 中所做的事情。这是我的 package.json 文件:
{
"name": "exampleNative",
"version": "0.0.1",
"private": true,
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"start": "react-native start",
"test": "jest",
"lint": "eslint ."
},
"dependencies": {
"react": "16.11.0",
"react-native": "0.62.2"
},
"devDependencies": {
"@babel/core": "^7.6.2",
"@babel/runtime": "^7.6.2",
"@react-native-community/eslint-config": "^0.0.5",
"babel-jest": "^24.9.0",
"eslint": "^6.5.1",
"jest": "^24.9.0",
"metro-react-native-babel-preset": "^0.58.0",
"react-test-renderer": "16.11.0"
},
"jest": {
"preset": "react-native"
}
}
I think this is happening because the child functional component has access to the scope of the parent functional component because it has been defined inside it.我认为这是因为子功能组件可以访问父功能组件的 scope,因为它已在其中定义。 It is a concept in JavaScript called 'Closures'.
这是 JavaScript 中称为“闭包”的概念。 You can read more about it in this blogpost (not mine).
你可以在这篇博文(不是我的)中阅读更多关于它的信息。 https://medium.com/@prashantramnyc/javascript-closures-simplified-d0d23fa06ba4
https://medium.com/@prashantramnyc/javascript-closures-simplified-d0d23fa06ba4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.