React+Typescript 父子组件事件传值

好 之前我们将 state 状态管理简单过了一下
那么 本文 我们来研究一下事假处理

点击事件上文中我们已经用过了 这里 我们就不去讲了 主要来说说 父子之间的事件

我们直接来编写一个小dom
我们父组件 编写代码如下

import Hello from "./components/hello";

function App() {
    
    
  const obtain = () => {
    
    
    console.log("调用了 父组件的obtain");
  };

  return (
    <div className="App">
      <Hello title="高阶组件" age={
    
    20} onObtain={
    
    obtain} />
    </div>
  );
}

export default App;

这里 我们定义了一个obtain函数
然后 给子组件绑定了一个 onObtain 事件 触发的函数时 指向本组件的obtain函数

然后 我们子组件编写代码如下

import * as React from "react";

interface IProps {
    
    
    title: string,
    age: number,
    onObtain: any
}

interface IState {
    
    
    count:number
}

export default class hello extends React.Component<IProps,IState> {
    
    

    public readonly state: Readonly<IState> = {
    
    
        count: 520
    }
    
    public constructor(props:IProps){
    
    
        super(props);
        this.clickHide = this.clickHide.bind(this);
        this.requestParent = this.requestParent.bind(this);
    }

    public clickHide(){
    
    
        this.setState({
    
    
            count: 200
        })
    }

    public requestParent() {
    
    
        this.props.onObtain();
    }


    public render() {
    
    
        return (
            <div>
                <div>{
    
     this.state.count }</div>
                <button onClick = {
    
     this.clickHide }>修改</button>
                <button onClick = {
    
     this.requestParent }>调用父组件函数</button>
            </div>
        )
    }
}

这里 我们写了个requestParent 点击按钮时触发
这里需要注意 我们函数直接在IProps中声明一下就好了 和 父组件传递的参数 props 一样
然后 我们为了方便类型直接给个any 任意类型
然后 当用户点击触发requestParent按钮时 我们调用父组件给的onObtain

我们运行项目然后点击按钮
在这里插入图片描述
可以看到 这个位置就没有任何问题 成功触发了

然后 我们进一步
写一个传递参数的
子组件的requestParent函数改成

public requestParent() {
    
    
    this.props.onObtain("小猫猫");
}

这样 我们就往onObtain中传了一个字符串 值为 小猫猫

然后 我们父组件的 obtain 改成这样

const obtain = (name:string) => {
    
    
   console.log(name);
};

这里 我们给obtain设置要接收一个参数 字符串类型的 键定义为name
然后 输出在控制台
我们再次运行项目 然后点击按钮
结果如下
在这里插入图片描述
也是没有任何问题

扫描二维码关注公众号,回复: 16298666 查看本文章

猜你喜欢

转载自blog.csdn.net/weixin_45966674/article/details/132427956
今日推荐