小编wen*_*jun的帖子

如何从远程 API 服务填充材料选择下拉列表?

我正在尝试使用来自远程 API 服务的值填充材料选择下拉列表。我一直在组件上得到一个空值或未定义的值。

这是使用 MEAN 堆栈和 Angular Material 的 Angular 7。我试过 compareWith 函数并记录值。我注意到该组件总是首先加载其值为空的值,然后是具有值的 API 服务。

<mat-form-field>
    <mat-select formControlName="company"  placeholder="Select 
Company" [(value)]="selectedCompany" [compareWith]="compareFn">
        <mat-option *ngFor="let lC of loadedCompanies" 
 [value]="lC.id">
          {{lC.name}}
        </mat-option>
    </mat-select>
</mat-form-field>

ngOnInit() {
  this.authStatusSub = this.authService
  .getAuthStatusListener()
  .subscribe(authStatus => {
      this.isLoading = false;
  });

  this.form = new FormGroup({
      id: new FormControl(null),
      company: new FormControl(this.loadedCompanies)
  });

  this.companyService.getCompanyList();
  this.companySub = this.companyService
  .getcompanyUpdateListener()
  .subscribe((companyData: {companies: Company[]}) => {
    this.isLoading = false;
    this.loadedCompanies =  companyData.companies;
  });
}

compareFn(c1: Company, c2: Company): boolean { …
Run Code Online (Sandbox Code Playgroud)

mean-stack angular-material angular angular7

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

如何在打字稿中的 forEach 下定义类型?

我有一个PersonTypes对象数组,并且只想在 forEach 循环中使用部分键。什么是更精确、更正确的打字稿编码来提供类型?我可以做一些类似的事情 people.forEach((person: Pick<PersonTypes, 'name' | 'gender'>people.forEach((person: PersonTypes) =>{ 或者 people.forEach((person: any) =>{ 什么是在打字稿中编码的正确方法

export type PersonTypes = {
  name: string;
  value: string;
  gender: boolean;
};
const people: PersonTypes[] = [
  {name: 'apl', value: 'apple', gender: true},
  {name: 'gal', value: 'google', gender: false},
]
people.forEach((person: Pick<PersonTypes, 'name' | 'gender'>) =>{
//people.forEach((person: PersonTypes) =>{
//people.forEach((person: any) =>{
  console.log(person.name);
  console.log(person.gender);
} )
Run Code Online (Sandbox Code Playgroud)

typescript typescript1.8 typescript-typings typescript2.0

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

如何在反应组件中使用样式组件

使用时完全是新手styled-components。我想知道它有什么用?样式化后应该如何实现组件生命周期方法?为了简单起见,我删除了所有其他样式。

import styled from 'styled-components';

const Button = styled.button`
  background-color: 'green'
`

export default Button;

Run Code Online (Sandbox Code Playgroud)

我想知道如何进一步研究这个Button组件?

传统上我们可以声明一个基于类的组件并实现一些生命周期方法,但现在有了 this styled-components,我不太确定如何将它们组合在一起,因为它们实际上是单个Button组件?

更新:

的完整源代码Button.js。通过使用下面的代码,所有样式都会消失,我无法理解问题

import React from 'react';
import styled from 'styled-components';
// import Button from 'react-bootstrap/Button';

import color from '../config/color';

const Button = ({ children, onPress }) => (
  <button type="button" onPress={onPress}>{children}</button>
);

const StyledButton = styled(Button)`
  width: 12rem;
  height: 54px;
  font-size: 1rem;
  background-color: ${(props) => {
    if (props.inverted) return 'white';
    if (props.disabled) …
Run Code Online (Sandbox Code Playgroud)

javascript css reactjs styled-components

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

我什么时候应该将 'className' 属性传递给反应组件?

一些 React 组件将className属性传递给子组件。我没有看到任何需要className在我的项目中作为支柱传递。

className为什么使用这个道具?我什么时候应该采用这种方法?

import styled from 'styled-components' 

const ReactComponent = ({ className }) => {
  return <div className={className}/>
}

const StyledComponent = styled(ReactComponent)``;
Run Code Online (Sandbox Code Playgroud)

reactjs styled-components

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

如何在 React 和 TypeScript 中切换布尔状态?

我是 React 和 TypeScript 的新手。

我想用处理函数切换布尔状态(真/假)。我读过其他关于如何在 ES6 中做到这一点的文章,但我不清楚如何在 TypeScript 中实现这一点。

到目前为止我有:

  const MyComponent = () => {
    const [collapseUpper, setCollapseUpper] = React.useState(true);

    const handleCollapse = () => {
      collapseUpper = !setCollapseUpper;
    };

    return (
       <Link onClick={handleCollapse}>More</Link>
       <Collapse in={collapseUpper}>
         //content
Run Code Online (Sandbox Code Playgroud)

但我无法让它发挥作用。

有人能指出我正确的方向吗?

javascript typescript reactjs react-hooks

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

如何在Angular 4的ngbDatepicker中禁用上一个日期?

我想禁用所有以前/过去的日期ngbDatepicker,我已经使用ngbDatepicker
我的HTML是:

<input required class="form-control" placeholder="dd-MM-YYYY" name="startDate" required ngbDatepicker #d="ngbDatepicker"
            [readonly]="true" [formControl]="formModel.controls.startDate" [ngClass]="{'has-error':!formModel.controls['startDate'].valid && formModel.controls['startDate'].touched}" />
Run Code Online (Sandbox Code Playgroud)

date angular angular4-forms

2
推荐指数
2
解决办法
4268
查看次数

使用 TypeScript 进行反应:类型不可分配给类型“IntrinsicAttributes”

我在 React 中有一个组件可以显示产品的分页。我无法弄清楚为什么当我尝试运行该应用程序时会收到此错误:

React with TypeScript: Type '{ postsPerPage: number; totalPosts: number; paginate: (pageNumber: number) => void; }' is not assignable to type 'IntrinsicAttributes & ProductListProps'.   Property 'postsPerPage' does not exist on type 'IntrinsicAttributes & ProductListProps'.
Run Code Online (Sandbox Code Playgroud)

我的代码:

const [currentPage, setCurrentPage] = useState(1);
const [postsPerPage] = useState(10);
const indexOfLastPost = currentPage * postsPerPage;
const indexOfFirstPost = indexOfLastPost - postsPerPage;
const currentPosts = data.slice(indexOfFirstPost, indexOfLastPost);


const paginate = (pageNumber: number) => setCurrentPage(pageNumber);

return (
      <>
        <h1 className="headline">SHOP</h1>
        <div className="total">Total: ${totalPrice}</div>

        <ProductList products={data} …
Run Code Online (Sandbox Code Playgroud)

javascript typescript reactjs react-typescript

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

无法读取未定义 React Hooks 的属性

我正在尝试使用 react hooks 创建一个搜索功能,但它一直返回错误:

无法读取未定义的属性

updateSearch每当我在输入字段中输入该函数时。

  const [search, setSearch] = React.useState('');
  const [searchResults, setSearchResults] = React.useState([]);

  const [state, setState] = React.useState({
    open: false,
    name: '',
    users:[]
  });

  useEffect(() => {
    getAllUsers();
  }, []);


  const getAllUsers = () => {
    fetch('/userinformation/', { 
      method: 'GET',
      headers: {'Content-Type':'application/json'}
    })
    .then(function(response) {
      return response.json()
    }).then(function(body) {
      console.log(body);
      setState({...state, users: body });
    })
  }

  const updateSearch = (event) => {
   setSearch(event.target.value)
  }

  React.useEffect(() => {
    const results = state.users.filter(user =>
      user.toLowerCase().includes(search)
    );
    setSearchResults(results);
  }, …
Run Code Online (Sandbox Code Playgroud)

javascript events reactjs react-hooks

2
推荐指数
1
解决办法
6267
查看次数

使用 TypeScript 推送到状态数组 React

我正在尝试通过 addTask 方法在我的任务数组中添加一个任务对象,该方法获取先前的状态并添加新任务,它可以工作,JSX但在我使用 TypeScript 时不起作用。我收到的错误是

Type 'ITask[] | undefined' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators.  TS2569
Run Code Online (Sandbox Code Playgroud)
import React, { Fragment } from 'react';

interface ITask {
    name: string;
    done: boolean;
}

interface IProps {

}

interface IState {
    newTask?: string;
    tasks?: Array<ITask>;
}

class App extends React.Component<IProps, IState>{
    constructor(props: any) {
        super(props);
        this.state = {
            newTask: '',
            tasks: []
        }
    }


    addTask(name:string) {
        this.setState(prevState => ({ …
Run Code Online (Sandbox Code Playgroud)

typescript reactjs

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

React eslint 错误?组件定义缺少显示名称

使用Reac.memo包裹我的功能组件,它可以流畅运行,但eslint总是让我想起了两个错误:

error    Component definition is missing display name  react/display-name

error    'time' is missing in props validation         react/prop-types
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

type Data = {
  time: number;
};
const Child: React.FC<Data> = React.memo(({ time }) => {
  console.log('child render...');
  const newTime: string = useMemo(() => {
    return changeTime(time);
  }, [time]);

  return (
    <>
      <p>Time is {newTime}</p>
      {/* <p>Random is: {children}</p> */}
    </>
  );
});
Run Code Online (Sandbox Code Playgroud)

我的整个代码:

import React, { useState, useMemo } from 'react';

const Father = () => {
  const [time, …
Run Code Online (Sandbox Code Playgroud)

typescript reactjs eslint

2
推荐指数
1
解决办法
6216
查看次数