React Native:为什么子组件可以访问父组件中useEffect内的变量?

时间:2020-05-23 14:16:46

标签: javascript reactjs react-native

我有以下代码。我无法理解为什么“ 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;

我注意到这只发生在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"
  }
}

1 个答案:

答案 0 :(得分:1)

我认为这是因为子功能组件可以访问父功能组件的范围,因为它已经在内部定义了。这是JavaScript中称为“关闭”的概念。您可以在此博客文章(不是我的文章)中了解更多有关它的信息。 https://medium.com/@prashantramnyc/javascript-closures-simplified-d0d23fa06ba4