Reactjs 反应类型脚本:将值从子级传递到父级
我希望能够从子组件调用函数Reactjs 反应类型脚本:将值从子级传递到父级,reactjs,typescript,Reactjs,Typescript,我希望能够从子组件调用函数printUrl。我在一个名为theurl的道具中传递函数,我不知道如何声明此道具类型,我不能在孩子的界面中将其保留为any,然后当我调用printUrl('testing')时,不会记录任何内容。我希望父函数printUrl注销testing 我觉得我完全误解了如何传递价值观。我得到的错误是未处理的拒绝(ReferenceError):未定义printUrl import React from 'react'; import { Child } from './chi
printUrl
。我在一个名为theurl
的道具中传递函数,我不知道如何声明此道具类型,我不能在孩子的界面中将其保留为any
,然后当我调用printUrl('testing')
时,不会记录任何内容。我希望父函数printUrl
注销testing
我觉得我完全误解了如何传递价值观。我得到的错误是未处理的拒绝(ReferenceError):未定义printUrl
import React from 'react';
import { Child } from './child';
const Parent: React.FC = () => {
const printUrl = (arg: string) => {
console.log(arg)
}
return (
<Child theurl={printUrl}/>
)
}
从“React”导入React;
从“/Child”导入{Child};
常量父项:React.FC=()=>{
常量printUrl=(参数:字符串)=>{
console.log(arg)
}
返回(
)
}
这孩子就像
import React from 'react';
interface PropsInterface {
theurl: any;
}
const Child: React.FC<PropsInterface> = (props: PropsInterface) => {
printUrl('testing')
}
从“React”导入React;
界面支撑面{
网址:any;
}
const Child:React.FC=(props:PropsInterface)=>{
printUrl('测试')
}
当您在
传递道具时,打印URL将重命名为URL。因此,在子组件中,您需要通过URL的名称来访问它
因此,您需要通过URL('testing')访问它,它应该可以正常工作
希望有帮助
编辑:根据讨论修改答案。您可以通过道具访问它。组件中的URL
:
const Child: React.FC<PropsInterface> = (props: PropsInterface) => {
props.theurl('testing')
}
const-Child:React.FC=(props:PropsInterface)=>{
props.theurl(“测试”)
}
printUrl
被分配给子成员theurl
。在要引用的子对象中,如下所示:
const Child: React.FC<PropsInterface> = (props: PropsInterface) => {
props.theurl('testing')
}
子级隐式返回void
,它不能是React组件的返回类型<代码>空是:
const Child: React.FC<PropsInterface> = (props: PropsInterface) => {
props.theurl('testing'); return null;
}
const-Child:React.FC=(props:PropsInterface)=>{
props.theurl('testing');返回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}/>
)
}
从“React”导入React;
界面支撑面{
printUrl:(url:string)=>void;
}
const Child:React.FC=(props:PropsInterface)=>{
props.printUrl(“测试”);返回null;
}
常量父项:React.FC=()=>{
常量printUrl=(参数:字符串)=>{
console.log(arg)
}
返回(
)
}
祝你的打字冒险好运 我得到的错误是
找不到名称'theurl'。ts(2304)
props。URL('testing')有效,对接口中的正确类型有什么想法吗?尝试使用props。URL
.interface props接口{theurl:Function;}
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}/>
)
}