react 子组件向父组件传值简单示例

父组件

data即为要向子组件 ExpressionTree 组件传递的值,

子组件

node.props.title,就相当于this.props.title,onSelect api 的理解请参考 ant design 组件的 树选择组件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
React 中,组件向父组件传值的常用方式是通过回调函数。具体步骤如下: 1. 在父组件中定义一个回调函数,用于接收组件传递的值。 2. 将该回调函数作为 props 传递给组件。 3. 在组件中,触发回调函数,并将要传递的值作为参数传递给该回调函数。 4. 在父组件中接收到组件传递的值,并在需要的时候将其更新到状态中。 示例代码如下: ``` // 父组件 import React, { useState } from 'react'; import ChildComponent from './ChildComponent'; function ParentComponent() { const [value, setValue] = useState(''); const handleChildValue = (childValue) => { setValue(childValue); }; return ( <div> <ChildComponent onChildValue={handleChildValue} /> <p>组件传递的值为: {value}</p> </div> ); } // 组件 import React from 'react'; function ChildComponent(props) { const handleClick = () => { props.onChildValue('Hello, Parent Component!'); }; return ( <button onClick={handleClick}>向父组件传递值</button> ); } ``` 在上面的示例代码中,组件 `ChildComponent` 定义了一个按钮,当点击该按钮时,会触发回调函数 `props.onChildValue` 并将要传递的值 `'Hello, Parent Component!'` 作为参数传递给该函数。在父组件 `ParentComponent` 中,定义了回调函数 `handleChildValue`,并将该函数作为 props 传递给组件 `ChildComponent`。当组件触发回调函数后,父组件会接收到组件传递的值,并将其更新到状态中,最终在页面上显示出来。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值