react 组件封装父传子传递函数的个人理解

2021-03-11  本文已影响0人  ticktackkk

父组件

import React, { useRef, useState } from "react";
import { Button } from "antd";
import { Test, Test2, Test3 } from './components/Test'
function App() {

  return (
    <div>
      <Test num={'点击'} style={{ width: '100px' }} onChange={(value1, value2) => {return value2*value1 }} />

      <Test2 num={'单击'} style={{ margin: '20px' }} onChange={value => { console.log(value); }} />

      <Test3 name='hello' onChange={() => { console.log(123); }} onChange1={() => { return 12 }} />

    </div>
  )

}
export default App

子组件

import { Button } from "antd";
import React, { Component } from 'react';


/**
 * 父传子 ,这里onChange默认为匿名函数,子组件函数里的参数可以在父组件拿到
 * 其次有了参数也要有参数执行的地方
 * 在父组件中要把这个参数当作一个属性 传入一个函数的类型
 * 
 */
function Test({ style = {}, onChange = function () { }, num = 1, type = 'primary' }) {
    return (
        <div>
            <Button style={style} type={type} >{onChange(2,3)}</Button>
        </div>
    )
}


function Test2({ style = {}, onChange = function () { }, num = 1, type = 'primary' }) {
    return (
        <div>
            <Button style={style} type={type} onClick={() => onChange('Test2')} >{num}</Button>
        </div>
    )
}

class Test3 extends Component {
    constructor(props) {
        super(props);
        this.state = {}
        console.log(this.props);
    }
    render() {
        return (
            <div>
                <Button onClick={this.props.onChange}>{this.props.name}</Button>
                <div>{this.props.onChange1()}</div>
            </div>
        );
    }
}
export { Test, Test2, Test3 }


上一篇 下一篇

猜你喜欢

热点阅读