You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中如何实现子组件向父组件传递状态数据

实现方案

React 中子组件向父组件传值的核心逻辑是状态提升 + 回调函数传参,你可以按下面的步骤修改代码:


步骤1:修改父组件 TestScreen

将location状态提升到父组件中定义,同时把状态更新方法作为props传递给子组件:

import React, { useState } from "react";
import { View, Text } from "react-native";
import TestComponent from "../components/TestComponent";

function TestScreen(props) {
  // 父组件中定义location状态
  const [location, setLocation] = useState("");
  return (
    <View>
      {/* 把更新location的方法作为props传给子组件 */}
      <TestComponent onLocationChange={setLocation} />
      <Text>{location}</Text>
    </View>
  );
}

export default TestScreen;

步骤2:修改子组件 TestComponent

删除子组件内部的location状态,点击时直接调用父组件传递过来的回调方法,把需要传递的值作为参数传入:

import React from "react";
import { View, Text, TouchableOpacity } from "react-native";

// 接收父组件传过来的onLocationChange回调
function TestComponent(props) {
  return (
    <View>
      <Text>Boiler</Text>
      <TouchableOpacity>
        <Text onPress={() => props.onLocationChange("Me")}>Click</Text>
      </TouchableOpacity>
    </View>
  );
}

export default TestComponent;

逻辑说明

  • 父组件把修改状态的方法通过props传给子组件,相当于给子组件开了一个修改父组件状态的入口
  • 子组件触发交互时,调用这个传入的方法,把要传递的数据作为参数传给该方法,父组件的状态就会对应更新,视图也会同步渲染

内容的提问来源于stack exchange,提问作者Reo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 02:45:03