【问题标题】:How to pass data from one component to another in react native如何在本机反应中将数据从一个组件传递到另一个组件
【发布时间】:2021-11-05 13:53:42
【问题描述】:

我有一个主组件,我在其中导入了一个组件,所以我想将一些数据从该导入的组件传递到主组件并显示它。这是一个示例代码: 这是我的主要文件:

import React from "react";
import { View, Text, StyleSheet, TouchableOpacity, Image } from "react-native";
import TestComponent from "../components/TestComponent";
function TestScreen(props) {
  return (
    <View>
      <TestComponent />
      <Text>{location}</Text>
    </View>
  );
}

export default TestScreen;

这是导入的组件:

import React from "react";
import { View, Text, StyleSheet, TouchableOpacity, Image } from "react-native";
function TestComponent(props) {
  const [location, setLocation] = useState("");
  return (
    <View>
      <Text>Boiler</Text>
      <TouchableOpacity>
        <Text onPress={() => setLocation("Me")}>Click</Text>
      </TouchableOpacity>
    </View>
  );
}

export default TestComponent;

现在我想从TestComponent 组件中获取location 钩子并将其用于TestScreen 组件,我该怎么做

【问题讨论】:

  • 来自 MVC 世界,看来您的 Controller 级别太低了

标签: javascript reactjs react-native react-hooks


【解决方案1】:

你应该将状态提升到父组件

function TestScreen(props) {
  const [location, setLocation] = useState("");
  return (
    <View>
      <TestComponent setLocation={setLocation} location={location}/>
      <Text>{location}</Text>
    </View>
  );
}


function TestComponent({ location, setLocation }) {
  return (
    <View>
      <Text>Boiler</Text>
      <TouchableOpacity>
        <Text onPress={() => setLocation("Me")}>Click</Text>
      </TouchableOpacity>
    </View>
  );
}

现在您可以访问父级中的location

【讨论】:

    【解决方案2】:

    您已经声明了数据并将数据作为 prop 传递给子组件,父数据可以是数组、对象、状态等:

    import React from "react";
    import { View, Text, StyleSheet, TouchableOpacity, Image } from "react-native";
    import TestComponent from "../components/TestComponent";
    function TestScreen(props) {
    const data = {name: 'im parent data'; otherProperty: 'im other property'}
      return (
        <View>
          <TestComponent />
        PASS DATA AS PROP
          <Text data={data}>{location}</Text>
        </View>
      );
    }
    
    export default TestScreen;
    

    使用点符号访问父数据:

    import React from "react";
    import { View, Text, StyleSheet, TouchableOpacity, Image } from "react-native";
    function TestComponent(props) {
      const [location, setLocation] = useState("");
      return (
        <View>
          <Text>Boiler</Text>
          <TouchableOpacity>
            <Text onPress={() => setLocation("Me")}>Click</Text>
          <h1>{props.data.name}</h1>
          <h1>{props.data.otherProperty}</h1>
          </TouchableOpacity>
        </View>
      );
    }
    
    export default TestComponent;
    

    【讨论】:

      猜你喜欢
      • 2015-09-28
      • 2019-07-05
      • 2021-04-23
      • 2019-11-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多