我有一个父组件,它将其子组件提供给子组件。子组件可以是节点或节点数组,并且根据它是节点还是节点数组,ChildComponent 中的子组件的呈现方式有所不同。但是,当我在 ParentComponent 中渲染 ChildComponent 时,出现以下 Typescript 错误:
\n\n\nTS2786:“ChildComponent”不能用作 JSX 组件。\xc2\xa0\xc2\xa0其返回类型\'Element | Element[]\' 不是有效的 JSX 元素。\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0Type \'Element[]\' 缺少类型 \'Element\' 中的以下属性: type、props、key
\n
请参阅下面的代码。如何渲染 ChildComponent 而不出现任何 Typescript 错误?谢谢!
\nimport React from \'react\';\nimport styles from \'./component.scss\';\n\ninterface Props {\n children: React.ReactChildren;\n}\n\nconst ChildComponent = ({ children }: Props): JSX.Element | JSX.Element[] => {\n if (React.Children.count(children)) {\n return React.Children.map(children, (child) => (\n <div className={styles.childContainer}>{child}</div>\n ));\n }\n\n return <div className={styles.singleContainer}>{children}</div>;\n};\n\nconst ParentComponent: React.FC<Props> = ({ children }) => (\n <div className={styles.container}>\n <ChildComponent>{children}</ChildComponent>\n </div>\n);\n\nexport …Run Code Online (Sandbox Code Playgroud) 尝试向我的组件添加ref时,出现 linting 错误:
TS2339:“导航”类型上不存在属性“childNavRef”
如何正确附加打字稿反应组件的参考?谢谢,您可以在下面看到组件以及 tsconfig 和 eslint 的代码。
导航.tsx:
import * as React from 'react';
interface MyState {
show: boolean;
}
export default class Navigation extends React.Component<{}, MyState> {
public constructor() {
super({});
this.state = {
show: true,
};
this.childNavRef = React.createRef();
}
public render(): React.ReactElement {
return (
<nav>
{
this.state.show
&& (
<div ref={this.childNavRef}>
This is a component
</div>
)
}
</nav>
);
}
}
Run Code Online (Sandbox Code Playgroud)
tsconfig.json:
{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": true, …Run Code Online (Sandbox Code Playgroud) 我正在使用prettier-eslint并尝试添加一个新的 eslint 规则来限制每行 jsx props 的数量:
eslintrc:
...
rules: {
'react/jsx-max-props-per-line': [2, { maximum: 1 }],
'react/jsx-indent-props': [2, 2],
'react/jsx-first-prop-new-line': [2, 'multiline'],
}
...
Run Code Online (Sandbox Code Playgroud)
但是,当我有如下代码时,它会得到更正,详细信息如下。我希望更正它而不是以下内容。jsx-wrap-multiline似乎是在寻找我正在寻找的解决方案,但它不处理函数参数。我怎样才能获得下面所需的 linting 呢?谢谢!
// Original Code
const foo = () => showModal(<SampleComponent title="hello world" id={123} />);
// Fixed Code
const foo = () =>
showModal(<SampleComponent
title="hello world"
id={123}
/>);
// Desired Fix
const foo = () => showModal(
<SampleComponent
title="hello world"
id={123}
/>
);
Run Code Online (Sandbox Code Playgroud)
完整的.estlintrc.js:
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: { …Run Code Online (Sandbox Code Playgroud) 我正在尝试编写一个测试,以确保在适当的情况下,使用特定消息调用特定函数(在本例中为哨兵函数)。但是,当我编写此测试时,它失败了,并且收到以下消息。如何正确模拟captureMessagein 函数handleError.test.js以确保使用"this is an error message."in 字符串正确调用它handleError.js?谢谢!
错误信息:
错误:expect(jest.fn())[.not].toHaveBeenCalledWith()
jest.fn() 值必须是模拟函数或间谍。收到:函数:[函数captureMessage]
处理错误.js:
import {captureMessage} from '@sentry/browser';
const handleError = (error) => {
if (error.name === "ApiError") {
captureMessage('this is an error message.');
}
};
export default handleError;
Run Code Online (Sandbox Code Playgroud)
处理错误.test.js:
import {captureMessage} from '@sentry/browser';
import handleError from '../handleError';
class ApiError extends Error {
constructor() {
super();
this.name = 'ApiError';
}
}
test('When an ApiError is returned with no action type, sentry is notified', () …Run Code Online (Sandbox Code Playgroud) 我需要对我的 less 文件使用内联 js,并且之前有一个 webpack 配置,其中包含类似这样的内容来启用内联 js:
module.exports = {
...
module: {
...
rules: [
...
{
test: /\.less$/,
use: [
{ loader: 'style-loader' },
{ loader: 'css-loader' },
{
loader: 'less-loader',
options: { javascriptEnabled: true },
},
],
},
],
},
};
Run Code Online (Sandbox Code Playgroud)
然而,该javascriptEnabled选项已被弃用,替代方案是使用语法@plugin并使用 js 插件。然而,我对文档以及如何准确地实现插件以及应该在我的 webpack 配置中实现哪个插件来替换这个现在已弃用的选项感到有点困惑,这样我仍然可以使用内联 js。我该怎么做呢?谢谢。
我有一个渲染 div 的组件,并在安装时将 youtube iframe 插入到该 div 中。我希望能够切换此组件以显示和隐藏它。但是,每当我“隐藏”组件(卸载它)时,我都会收到以下错误消息:
无法在“Node”上执行“removeChild”:要删除的节点不是此节点的子节点。
我怎样才能卸载这个组件?谢谢。
索引.tsx:
import * as React from "react";
import ReactDOM from "react-dom";
declare global {
interface Window {
YT: any;
onYouTubeIframeAPIReady: Function;
}
}
const YoutubePlayer: React.FC = () => {
const videoFrameId = "youtube-player-1";
const onPlayerReady = (event: { [key: string]: any }): void => {
event.target.playVideo();
};
React.useEffect(() => {
const loadVideo = (): void => {
new window.YT.Player(videoFrameId, {
videoId: "5qap5aO4i9A",
events: {
onReady: onPlayerReady
}
}); …Run Code Online (Sandbox Code Playgroud) 为了在打字稿枚举中使用项目的子集,我们执行以下操作:
enum Operator {
EQUAL = 'EQUAL',
NOT_EQUAL = 'NOT_EQUAL',
LESS = 'LESS',
GREATER = 'GREATER',
}
type EqualOperators = Exclude<Operator, Operator.LESS | Operator.GREATER>
Run Code Online (Sandbox Code Playgroud)
有什么办法可以让我EqualOperators成为一个enum而不是一个type,这样我就可以在脚本中使用它吗?
澄清一下,当我说“在脚本中使用它”时,我的意思是能够enum在 javascript 函数中使用值,而你不能使用它types,例如这样的:
enum Operator {
EQUAL = 'EQUAL',
NOT_EQUAL = 'NOT_EQUAL',
LESS = 'LESS',
GREATER = 'GREATER',
}
function getOperator() {
if (Operator.EQUAL) {
return "=";
}
if (Operator.NOT_EQUAL) {
return "!=";
}
throw new Error('invalid operator');
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
在React组件内部,我希望能够计算每个子容器的总高度,在这种情况下,这是三个h3元素,以便在为其高度动画化时可以计算父div的确切高度。我已经看过基本js以及使用组件安装方法的示例,但是如何仅使用JavaScript来获取这些元素的高度呢?
class Div extends React.Component {
render() {
return (
<div>
<h3>Description One</h3>
<h3>Description Two</h3>
<h3>Description Three</h3>
</div>
);
}
}
ReactDOM.render(<Div />, app);Run Code Online (Sandbox Code Playgroud)
div {
background-color: pink;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="app"></div>Run Code Online (Sandbox Code Playgroud)
我正在尝试创建一个具有事件侦听器的 TypeScript React 组件。但是,当我这样做时,我收到以下错误消息:
TS2345:“(event: React.MouseEvent) => void”类型的参数不可分配给“EventListenerOrEventListenerObject”类型的参数。
我是否缺少某种类型的检查?谢谢。您可以在下面看到组件代码。
样本组件.tsx:
import * as React from 'react';
interface MyState {
onClick: boolean;
}
export default class SampleComponent extends React.Component<{}, MyState> {
private divRef: React.RefObject<HTMLDivElement>;
public constructor() {
super({});
this.state = {
onClick: false,
};
this.divRef = React.createRef();
this.handleClickOutside = this.handleClickOutside.bind(this);
}
public componentDidMount(): void {
document.addEventListener('mousedown', this.handleClickOutside);
}
public handleClickOutside(event: React.MouseEvent<HTMLElement>): void {
if (
this.divRef.current.contains(event.target as Node)
) {
this.setState({ onClick: true });
}
}
public render(): React.ReactElement {
return …Run Code Online (Sandbox Code Playgroud) 如何在 Go 中创建仅限于特定字符串值列表的自定义类型?例如
type Suit = "Spade" | "Diamond" | "Club" | "Heart"
Run Code Online (Sandbox Code Playgroud) 请参阅此codesandbox。
我有一个父 div 需要处理可拖动事件(例如将文件拖到其上时)。当onDragEnter调用时,我希望背景颜色改变。但是,我有一个子 div,当将其悬停在其上时,会调用父 div 的onDragLeave事件。我尝试使用此子 div 的 ref 来确定事件目标是否包含在子 div 中,但这似乎不起作用。如何避免 React 中的子 div 调用该onDragLeave事件?谢谢!
import React, { useState } from 'react';
const App = () => {
const [dragOver, setDragOver] = useState(false);
const preventDefaults = (event) => {
event.preventDefault();
event.stopPropagation();
};
const onDragEnter = (event) => {
preventDefaults(event);
console.log('ENTER');
if (!dragOver) {
setDragOver(true);
}
};
const onDragLeave = (event) => {
preventDefaults(event);
console.log('LEAVE');
setDragOver(false);
};
return (
<div
data-testid="document-upload" …Run Code Online (Sandbox Code Playgroud) 我有以下文件:
样本函数.ts:
export default (x: number) => x * 2;
Run Code Online (Sandbox Code Playgroud)
测试文件:
import sampleFunction from './sampleFunction';
export default () => {
const n = sampleFunction(12);
return n - 4;
};
Run Code Online (Sandbox Code Playgroud)
测试文件.test.ts:
import testFile from './testFile';
const mockFn = jest.fn();
jest.mock('./sampleFunction', () => ({
__esModule: true,
default: mockFn,
}));
test('sample test', () => {
testFile();
expect(mockFn).toBeCalled();
});
Run Code Online (Sandbox Code Playgroud)
当我运行时testFile.test.ts,出现以下错误:
TypeError: (0 , _sampleFunction).default is not a function
Run Code Online (Sandbox Code Playgroud)
sampleFunction.ts当 Jest 有默认导出函数时,我如何使用它进行模拟?
我想使用 Jest 和 Enzyme 编写一个测试,测试具有事件侦听器的组件,这样当给定 html 元素外部发生 mousedown 事件时,就会发生更改(在本例中,状态值被切换)。我正在使用 jest 来模拟事件侦听器并模拟 mousedown 事件,但是,当我尝试运行此测试时,我收到以下错误消息:
TypeError:无法在“Node”上执行“contains”:参数 1 不是“Node”类型。
显然,我认为<div />当我用 模拟 mousedown 事件时,这不是我应该提供的正确值map.mousedown({ target: <section /> });。如何正确模拟组件外部发生的 mousedown 事件?您可以看到下面的代码。谢谢!
示例组件.jsx:
import * as React from 'react';
const SampleComponent = () => {
const [state, setState] = React.useState(false);
const ref = React.useRef(null);
const handleClickOutside = (event) => {
if (
!ref.current.contains(event.target)
) {
setState(true);
}
};
React.useEffect(() => {
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
});
return ( …Run Code Online (Sandbox Code Playgroud) javascript ×8
reactjs ×8
typescript ×6
jestjs ×3
eslint ×2
html ×2
css ×1
dom ×1
enzyme ×1
go ×1
less ×1
less-loader ×1
prettier ×1
webpack ×1
youtube-api ×1