gpt4 book ai didi

reactjs - 在 typescript 中使用 defaultProps 的 forwardRef

转载 作者:行者123 更新时间:2023-12-04 13:35:15 25 4
gpt4 key购买 nike

我正在尝试在 forwardRef 中使用 defaultProps。
当我在没有 forwardRef 的情况下使用 MessageBox 时,它与 defaultProps 配合得很好。
但是,当我使用 forwardRef 时会发生错误。如何解决?
typescript :3.4.5“ react ”:“^ 16.8.6”,

import React, { forwardRef } from "react";

export interface MessageBoxProps {
test: string;
children: any;
}

const defaultProps: Partial<MessageBoxProps> = {
test: "test"
};

const MessageBox = forwardRef<HTMLDivElement, MessageBoxProps>((props, ref) => {
return <p>{props.test}</p>;
});

MessageBox.defaultProps = defaultProps;

export default MessageBox;

export default function App() {
const ref = React.useRef<HTMLDivElement>(null);
return (
<div className="App">
<Test ref={ref} />
</div>
);
}
Type '{ ref: RefObject<HTMLDivElement>; }' is missing the following properties from type 'MessageBoxProps': test, children
https://codesandbox.io/s/forwardref-with-typescript-knhu3?file=/src/App.tsx:83-244

最佳答案

尝试:

export interface MessageBoxProps extends React.AllHTMLAttributes<HTMLDivElement>
{
test?: string;
}
它对我有用。现在您还可以设置 children、href、onClick 和其他属性。
这是 fork 的沙箱链接: https://codesandbox.io/s/forwardref-with-typescript-forked-sn0u3?file=/src/App.tsx

关于reactjs - 在 typescript 中使用 defaultProps 的 forwardRef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62527337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com