【问题标题】:React Typescript: Pass value from child to parentReact Typescript:将值从孩子传递给父母
【发布时间】:2019-12-08 09:20:16
【问题描述】:

我希望能够从子组件调用函数printUrl。我在一个名为theurl 的道具中传递函数我不知道如何声明这个道具类型,我不能在孩子的界面中将它保留为any,然后当我调用printUrl('testing') 时没有任何记录。我期待父函数printUrl 注销testing

我觉得我完全误解了如何传递价值观。我得到的错误是Unhandled Rejection (ReferenceError): printUrl is not defined

import React from 'react';
import { Child } from './child';

const Parent: React.FC = () => {
    const printUrl = (arg: string) => {
        console.log(arg)
    }
    return (
    <Child theurl={printUrl}/>
    )
}

和孩子一样……

import React from 'react';

interface PropsInterface {
  theurl: any;
}
const Child: React.FC<PropsInterface> = (props: PropsInterface) => {
 printUrl('testing')
}

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    当你在&lt;Child theurl={printUrl}/&gt; 传递道具时,printUrl 被重命名为 theurl。因此,在子组件中,您需要通过 URL 的名称来访问它。

    因此,您需要通过theurl('testing') 访问它,它应该可以正常工作。

    希望对你有帮助!

    编辑:根据讨论修改答案。您可以在组件中以props.theurl 的形式访问它:

    const Child: React.FC<PropsInterface> = (props: PropsInterface) => {
     props.theurl('testing')
    }
    

    【讨论】:

    • 我得到的错误是Cannot find name 'theurl'.ts(2304)
    • props.theurl('testing') 有效,对界面中的正确类型有任何想法吗?
    • 尝试使用props.theurl
    • interface PropsInterface { theurl: Function; }
    【解决方案2】:

    printUrl 被分配给子成员 theurl。在你想像这样引用它的孩子中:

    const Child: React.FC<PropsInterface> = (props: PropsInterface) => {
     props.theurl('testing')
    }
    

    您还可以将theurl 作为函数强输入:

    interface PropsInterface {
      theurl: (url:string) => void;
    }
    

    Child 隐式返回 void,它不能是 React 组件的返回类型。 null 是:

    const Child: React.FC<PropsInterface> = (props: PropsInterface) => {
     props.theurl('testing'); return null;
    }
    

    最好将函数道具命名为动词。

    import React from 'react';
    
    interface PropsInterface {
      printUrl: (url:string) => void;
    }
    
    const Child: React.FC<PropsInterface> = (props: PropsInterface) => {
      props.printUrl("testing"); return null;
    }
    
    
    const Parent: React.FC = () => {
        const printUrl = (arg: string) => {
            console.log(arg)
        }
        return (
        <Child printUrl={printUrl}/>
        )
    }
    

    祝你在打字稿冒险中好运!

    【讨论】:

      猜你喜欢
      • 2018-06-29
      • 2020-07-22
      • 1970-01-01
      • 2021-09-13
      • 2019-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-14
      相关资源
      最近更新 更多