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

ReactJS:如何将Child Component输入值传递给Parent Component

子组件向父组件传递输入值的解决方案

没问题!这是组件通信里最常见的场景之一,核心思路其实很简单:父组件提供一个回调函数给子组件,子组件在输入值变化时调用这个函数,把当前值传递回去。我给你分React和Vue两种主流框架分别举例:

React 实现

父组件代码

父组件需要先定义状态来存储子组件传来的值,同时创建一个回调函数,把这个函数作为props传给子组件:

import { useState } from 'react';
import ChildComponent from './ChildComponent';

function ParentComponent() {
  // 用状态保存子组件的输入值
  const [childInputValue, setChildInputValue] = useState('');

  // 回调函数,接收子组件传递的值并更新状态
  const handleChildInputChange = (value) => {
    setChildInputValue(value);
    // 这里可以添加你需要的其他逻辑,比如校验、提交等
    console.log('从子组件拿到的值:', value);
  };

  return (
    <div>
      <h3>父组件显示子组件输入值: {childInputValue}</h3>
      {/* 将回调函数通过props传给子组件 */}
      <ChildComponent onInputChange={handleChildInputChange} />
    </div>
  );
}

export default ParentComponent;

子组件代码

子组件监听输入框的变化,在触发时调用父组件传来的回调函数,把当前输入值传过去:

function ChildComponent({ onInputChange }) {
  const handleInputChange = (e) => {
    const inputValue = e.target.value;
    // 调用父组件的回调函数,传递输入值
    onInputChange(inputValue);
  };

  return (
    <div>
      <input 
        type="text" 
        placeholder="在子组件输入值试试" 
        onChange={handleInputChange} 
      />
    </div>
  );
}

export default ChildComponent;

Vue 实现

父组件代码

父组件通过自定义事件绑定一个处理函数,子组件触发这个事件时就能传递值过来:

<template>
  <div class="parent">
    <h3>父组件显示子组件输入值: {{ childInputValue }}</h3>
    <!-- 绑定自定义事件,指定处理函数 -->
    <ChildComponent @input-change="handleChildInputChange" />
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  components: { ChildComponent },
  data() {
    return {
      childInputValue: ''
    };
  },
  methods: {
    handleChildInputChange(value) {
      this.childInputValue = value;
      console.log('从子组件拿到的值:', value);
    }
  }
};
</script>

子组件代码

子组件监听输入事件,通过$emit触发父组件绑定的自定义事件,并传递输入值:

<template>
  <div class="child">
    <input 
      type="text" 
      placeholder="在子组件输入值试试" 
      @input="handleInputChange" 
    />
  </div>
</template>

<script>
export default {
  methods: {
    handleInputChange(e) {
      const inputValue = e.target.value;
      // 触发自定义事件,把值传给父组件
      this.$emit('input-change', inputValue);
    }
  }
};
</script>

核心总结

不管是React还是Vue,本质都是遵循单向数据流的原则:子组件不直接修改父组件的状态,而是通过触发父组件提供的方法来传递数据,这样能保证组件的独立性和代码的可维护性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:01:00