react子组件向父组件传值

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
  <script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
  <script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
</head>

<body>
  <div id="root"></div>
  <script type="text/babel">
    class Father extends React.Component {
      handleGetMsg = (value) => {
        console.log(value)
        this.setState({
          test: value
        })
      }
      state = {
          
        }
      render() {
        return (
          <div>
            <p>从子组件中接收到得数据: {this.state.test}</p>
            <Child getMsg={this.handleGetMsg}/>
          </div>
        )
      }
    }

    class Child extends React.Component {
      state = {
        val: 'haha'
      }
      handleClick = () => {
        this.props.getMsg(this.state.val)
      }
      render() {
        return (
          <div>
            <button onClick={this.handleClick}>子组件</button>
          </div>
        )
      }
    }
    ReactDOM.render(<Father />, document.getElementById('root'))

  </script>
</body>

</html>
  1. 在父组件中定义一个函数,该函数用于处理传递过来得值(比如用于修改父组件中state得数据)
  2. 在子组件调用部分通过属性绑定得形式绑定该函数(在子组件中就可以通过this.props.属性名就可以拿到该函数)
  3. 在子组件中绑定触发传值得事件比如点击事件,在事件处理函数中通过this.props.属性名()调用父组件中定义得方法
  4. 就可以在父组件中拿到传递过来得值进行使用
  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值