【发布时间】:2022-01-12 06:04:08
【问题描述】:
我是 React 和 Typescript 的新手。当我尝试将道具从父母传递给孩子时,我收到错误:
TS2322: Type '{ changeValue: () => void; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }'. Property 'changeValue' does not exist on type 'IntrinsicAttributes & { children?: ReactNode; }'.
父.tsx:
import * as React from 'react';
import { Child } from '../components/Child';
const Parent: React.FC = () => {
function changeValue() {
console.log("hello");
}
return (
<div>
<Child changeValue={changeValue}/>
</div>
);
};
export default Parent;
Child.tsx:
import * as React from 'react';
import { useState } from 'react';
export const Child: React.FC = (props) => {
const [textValue, setTextValue] = useState(
'let name; \n' + 'let age; \n' + 'name = 5;'
);
return (
<div>
<textarea
id="details"
name="details"
value={props.data}
onChange={() => changeValue}
/>
</div>
);
};
我在 stackoverflow 中看到了一些答案,但无法弄清楚错误出现的原因。我不确定我在这里缺少什么。 提前致谢。
【问题讨论】:
-
您忘记在子组件中调用带括号的函数:
onChange={() => props.changeValue()} -
添加后我也收到错误:TS2339:属性'changeValue'不存在类型'{孩子?:ReactNode; }'。
-
在继续前进之前最好退后一步:您究竟希望您的 Child 组件做什么(您希望它如何表现)? (同样的问题也适用于父母。)将此目标添加到您的问题中,以便我们知道如何帮助您获得正确的组件类型。
-
当子文本区域发生一些变化时,我想更新父文本区域中的某些内容。这就是为什么我试图传递一个父方法并将在子的 onChange 上执行。
-
另一件事,是否可以将父函数传递给子函数并执行子函数的更改?
标签: reactjs typescript components parent-child