标签: react-tsx

如何使用CRA将类型声明添加到react-typescript项目

我用命令CRA创建了一个React Typescript项目 yarn create react-app my-app --typescript

现在,我安装了一个模块foo,默认情况下,该类型没有任何类型,不在defentlytyped存储库中。

即在一个组件中,我有

import {bar} from 'foo';
Run Code Online (Sandbox Code Playgroud)

引发错误 Type error: Could not find a declaration file for module 'foo'. '/*/node_modules/foo/dist/entry.js' implicitly has an 'any' type.

foo.d.ts在项目根目录的types文件夹中创建了

declare module 'foo'{ import * as React from 'react' }
Run Code Online (Sandbox Code Playgroud)

只是具有fooas类型,any但仍然会得到相同的错误。似乎任何编译器(webpack,其他编译器)都未在types文件夹中找到声明

如何为项目添加自定义类型声明?

type-declaration typescript reactjs create-react-app react-tsx

5
推荐指数
1
解决办法
536
查看次数

监视 redux 调度方法

我是一个开玩笑的新手,我正在为我的 React 应用程序编写单元测试,该应用程序使用 redux 并使用 Typescript 编写。

我的容器组件包含这段代码:

const mapDispatchToProps = (dispatch: Dispatch<any>) => ({
    onSelectScenario: (selectedScenario: any) => {
        dispatch(selectScenario(selectedScenario));
    }
});
Run Code Online (Sandbox Code Playgroud)

我想编写一个单元测试,检查当我从测试 ( onSelectScenario) 调用此道具时,dispatch将使用正确的参数调用该方法。

知道如何监视这个吗dispatch

这是我的单元测试,我在其中调用 prop 方法:

it('should dispatch', () => {
    component.props().onSelectScenario('New Selected Scenario');
});
Run Code Online (Sandbox Code Playgroud)

这是测试的设置,我在其中定义提供模拟商店的容器组件:

const mockStore = configureMockStore();
let store = mockStore({
    scenarios: ['Scenario 1', 'Scenario 2']
});
let component: ShallowWrapper<any, any>;

describe('ScenarioListGroupContainer Component', () => {
    beforeEach(() => {
        component = shallow(<ScenarioListGroupContainer store={store} />);
    });
    // ... …
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs redux react-redux react-tsx

4
推荐指数
1
解决办法
1万
查看次数

接口 MouseEvent 和 TouchEvent 的 React Typescript 事件类型

我正在尝试编写一个函数来处理mousetouch事件。通过结合两个接口React.TouchEventReact.MouseEvent,例如:

onStart = (event: React.TouchEvent | React.MouseEvent) => {
    event.persist();
    console.log('event ', event);
    if (event.touches) {
        console.log(event.touches);
    }
    if (event.screenX) {
        console.log(event.screenX);
    }
};
Run Code Online (Sandbox Code Playgroud)

日志给了我预期的输出,我没有收到任何控制台错误,它按照我的预期运行。但是我的编辑器出现错误:

错误:(94, 22) TS2339:属性“screenX”不存在于类型“MouseEvent | 触摸事件'。“TouchEvent”类型上不存在属性“screenX”。

错误:(90, 13) TS2339:“MouseEvent |”类型上不存在“touches”属性 触摸事件'。“MouseEvent”类型不存在“touches”属性。

我该如何使用这两种intefacesReact.TouchEventReact.MouseEvent没有这一切的错误?

typescript reactjs react-tsx

4
推荐指数
1
解决办法
5011
查看次数

添加功能组件作为属性的功能组件中“属性不存在”?

我将 React 与 Typescript 和函数式方法结合使用。

const Divider: React.FunctionComponent<CardDividerProps> = (props: CardDividerProps) => (
   <div>
      divider
   </div>
);

const Card: React.FunctionComponent<CardProps> = (props: CardProps) => (
   <div>
      card
   </div>
);

Card.Divider = Divider; //Property 'Divider' does not exist on type 'FunctionComponent<CardProps>'.
Run Code Online (Sandbox Code Playgroud)

如果我从卡中删除显式类型,它就会起作用。但我想用 React.FunctionComponent 来指定它......可能吗?

我想我可以创建一个类型:

type CardWithDividerComponent = {
    (props: CardProps): JSX.Element;
    defaultProps: CardProps;
    Divider: React.FunctionComponent<CardDividerProps>;
}
Run Code Online (Sandbox Code Playgroud)

但这是唯一的解决方案吗?有什么解决办法React.FunctionComponent吗?

typescript reactjs react-tsx react-functional-component react-typescript

4
推荐指数
1
解决办法
2934
查看次数

在 React Material-UI DataGrid 中获取复选框选择上的行项目

我从 API 获取数据并使用 React Material-UI Data Grid 显示它。我启用了复选框选择,我想获取所选行的特定单元格项目并将它们保存在列表中。

例如在下图中,如果我点击第一行的复选框,我想在列表中添加“当前位置”,然后如果我点击第二行,我想要第二行的当前位置添加到现有的列表。

在此处输入图片说明

下面是我当前的代码

<DataGrid
   rows={rows}
   columns={columns}
   checkboxSelection     
   onSelectionModelChange={itm => console.log(itm)}
/>
Run Code Online (Sandbox Code Playgroud)

但我得到这样的输出

在此处输入图片说明

我对 React 非常陌生,我不确定如何获取所选行的当前位置值并将其添加到列表中。

datagrid reactjs material-ui react-tsx

4
推荐指数
3
解决办法
4820
查看次数

如何使用 typescript、react 和 jest 进行手动模拟?

我试图使用 jest 来模拟 React 组件使用的钩子的返回值,但我无法让它工作。考虑价格标签部分。它所做的只是渲染从挂钩返回的价格usePrice

usePrice.ts

export default function usePrice() {
  return 1337;
}
Run Code Online (Sandbox Code Playgroud)

PriceTag.tsx

import React from 'react';
import usePrice from './usePrice';

export default function PriceTag() {
  const price = usePrice();

  return <p>Price: {price}</p>
}
Run Code Online (Sandbox Code Playgroud)

在测试中,我断言显示了正确的价格。由于我想为此组件创建多个测试,因此setPrice使用帮助器为每个测试设置下一个返回值。

__mocks__/usePrice.ts

let price = 58008;

export function setPrice(newPrice) {
  price = newPrice;
}

export default function usePrice() {
  return price;
}
Run Code Online (Sandbox Code Playgroud)

PriceTag.test.tsx

import { render } from '@testing-library/react';
import React from 'react';
import PriceTag …
Run Code Online (Sandbox Code Playgroud)

mocking typescript reactjs react-tsx ts-jest

4
推荐指数
1
解决办法
3907
查看次数

在 React DND 中使用句柄

我正在使用 React-dnd,并尝试创建一个具有可排序行的表,该表只能从手柄中拖动,手柄是右侧的一个小跨度。

他们在这里给出的示例 https://react-dnd.github.io/react-dnd/examples/customize/handles-and-previews

不显示任何排序。我可以使用不同的预览让句柄工作,问题是如果我使用他们提供的代码,用于对表进行排序的拖放区仅当我将其直接悬停在跨度上时才起作用,而不是像应有的那样悬停在行上。

我的代码:

 const dragRef  = useRef<any>(null)


const [{ isDragging }, drag, preview] = useDrag({
    type: DragTypeEnum.ENTRY,
    item: () => {
        return { id: props.id, index: props.sequence }
    },
    collect: (monitor: any) => ({
        isDragging: monitor.isDragging(),
    }),
});


const [{ handlerId }, drop] = useDrop({
    accept: DragTypeEnum.ENTRY,
    collect(monitor) {
        return {
            handlerId: monitor.getHandlerId(),
        }
    },
    hover(item: DragItem, monitor: DropTargetMonitor) {
        if (!dragRef.current) {
            return
        }
        const dragId = item.id
        const hoverId = props.id;

        // Don't replace items …
Run Code Online (Sandbox Code Playgroud)

react-dnd react-tsx react-hooks

4
推荐指数
1
解决办法
4439
查看次数

如何在React TS中应用useRef()?

目标:
单击按钮时从文本框中获取值

问题:
该值不显示在控制台中。

"Uncaught Error: Function components cannot have string refs. We recommend using useRef() instead"
Run Code Online (Sandbox Code Playgroud)

在这种情况下如何应用 useRef() ?

Stackblitz
https://stackblitz.com/edit/react-ts-mcn4jd?file=index.tsx

信息:
*React TS 新手

谢谢你!

import React from 'react';
import logo from './logo.svg';
import './App.css';

function App() {

  function test() {
    // Get the value and display it at consol
    //var name = refs.mytext.value;
    
    var element = document.getElementById("ddddd");


    console.log(element);
  }

  return (
    <div className="App">
      <input type="text" id="ddddd" ref="mytext" />
      <button onClick={() => test()}>Add</button>
    </div>
  );
}

export default …
Run Code Online (Sandbox Code Playgroud)

typescript react-tsx react-hooks

4
推荐指数
1
解决办法
1万
查看次数

React Typescript,从外部脚本调用函数

在我的 React 应用程序中,我从服务器获取自定义 javascript 文件并将其作为script标签附加到document.

这个新添加的自定义文件包含一个名为 的方法manipulator。现在,在其中一个组件中,我想调用该函数。据我所知,该函数应该存在于window全局对象中。

if(documnet.getElementById('customJsId')){ // check if the script tag exists in document
 window.manipulator(); // which I get Property 'iframeManipulator' does not exist on type 'Window'.ts(2339)
}
Run Code Online (Sandbox Code Playgroud)

但这里我得到编译器错误

类型“Window”上不存在属性“manipulator”。ts(2339)

这是完全合乎逻辑的,但我没有找到一种方法来创建扩展接口window或任何其他方法来告诉编译器window调用中有一个可选函数manipulator

任何帮助表示赞赏。

  ----------Just in case--how the script is added to document--------------
  loadProjectCustomJS() {
    runInAction(async () => {
      thisfetchProjectJs().then((doc) => {
        const body: HTMLBodyElement = document.getElementsByTagName('body')[0];
        const customjs: HTMLScriptElement = document.createElement('script');
        customjs.type = 'text/javascript'; …
Run Code Online (Sandbox Code Playgroud)

javascript dom typescript react-tsx global-functions

3
推荐指数
1
解决办法
4246
查看次数

突出显示导航窗格中的选定项目

参考https://developer.microsoft.com/en-us/fabric#/controls/web/nav下的示例“带有嵌套链接的导航” ,单击导航项时,我想突出显示该项目。我已将 url 设置为“ ”,这样单击某个项目不会执行任何操作。但是,我希望该项目在单击时突出显示。我该怎么做呢?任何指示都会有帮助。

import * as React from 'react';
import { Nav,INavStyles } from 'office-ui-fabric-react/lib/Nav';
import { initializeIcons } from '@uifabric/icons';
initializeIcons();

    const navStyles: INavStyles = {
  root:{
      boxSizing: 'border-box',
      border: '1px solid lightgrey',
      overflowY: 'auto',
      height: 300
  },
  chevronButton: {
      height: 30
  },
  chevronIcon:{
      height: 30,
      lineHeight: 30
  },
  compositeLink: {}, 
  group:{}, 
  groupContent: {},
  link: {},
  linkText:{},
  navItem:{}, 
  navItems:{
    margin: 0
  },
};

export const NavNestedExample1: React.FunctionComponent = () => {
  return (
    <Nav
      styles={navStyles}
      ariaLabel="Nav …
Run Code Online (Sandbox Code Playgroud)

reactjs office-ui-fabric react-tsx

3
推荐指数
1
解决办法
1713
查看次数