标签: react-component

React:render() 之后和子构造函数之前的函数调用

我有一个名为Parent的组件,其中有另一个名为Child 的组件:

<Parent>
  <Child/>
</Parent>
Run Code Online (Sandbox Code Playgroud)

所以生命周期如下:

  1. 父构造函数
  2. 父母的渲染()
  3. 子构造函数
  4. 孩子的渲染()
  5. 孩子已安装
  6. 父级已挂载

我可以在第 2 步之后和第 3 步之前以某种方式进行额外的父初始化吗?

更新:

<Parent>
  <Child/>
</Parent>
Run Code Online (Sandbox Code Playgroud)
class ThirdPartyLib {
  init(elementId) {
    console.log(`initializing element: ${elementId}`);
    // element with #id: elementId should exist!
    // document.getElementById(elementId).style.color = "red";
  }
}

class Parent extends React.Component {
    constructor(props) {
        super(props);
        console.log("Parent's constructor");
    }

    render() {
        console.log("rendering Parent");
        new ThirdPartyLib().init("parent");
        return (
            <div id="parent">Parent: {this.props.name}
                <Child name="Sara"/>
            </div>
        );
    }

    componentDidMount() {
        console.log("Parent is mounted");
    }
} …
Run Code Online (Sandbox Code Playgroud)

reactjs react-lifecycle react-component

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

为多级状态对象反应 setState

我正在尝试更新包含多个级别的状态对象。请参阅此示例https://codesandbox.io/s/oq9kp9vy5y

问题是,render 方法中的值不会更新……只有第一个。我可以强制更新还是有更好的方法?

谢谢卡斯帕

setstate reactjs react-component react-state-management react-state

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

在异步调用完成后呈现部分 React 函数组件

我将 material-ui 与 React 功能组件一起使用并使用其自动完成组件。我自定义了它,每当我更改输入字段中的文本时,我希望该组件呈现新的搜索结果。

callAPI("xyz")
Run Code Online (Sandbox Code Playgroud)

我在 action 中调用 API 并使用 xyz 参数,我正在从这个函数组件调用 dispatch 方法。

这里的问题是,当组件进行调用时,它应该等待 API 响应然后呈现结果,但它得到了一个未解决的承诺,所以它无法呈现。

<Paper square>
    {callAPI("xyz").results.map(
        result => console.log(result);
    )}
</Paper>
Run Code Online (Sandbox Code Playgroud)

由于结果是一个未解决的承诺,它将无法映射。我需要某种方法来仅在数据可用时调用地图,或者在数据存在之前显示一些文本,然后在获取数据后进行更改。

任何纠正此代码的建议都将非常有帮助。

编辑:

function IntegrationDownshift() {
    return (
        <div>
            <Downshift id="downshift-simple">
                {({
                    getInputProps,
                    getItemProps,
                    getMenuProps,
                    highlightedIndex,
                    inputValue,
                    isOpen,
                    selectedItem
                }) => (
                    <div>
                        {renderInput({
                            fullWidth: true,
                            InputProps: getInputProps({
                                placeholder: "Search users with id"
                            })
                        })}

                        <div {...getMenuProps()}>
                            {isOpen ?
                                 <Paper square>
                                {callAPI(inputValue).users.map(
                                    (suggestion, index) =>
                                        renderSuggestion({
                                            suggestion,
                                            index,
                                            itemProps: getItemProps({
                                                item:
                                                    suggestion.userName
                                            }),
                                            highlightedIndex, …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-async material-ui react-component

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

是否可以编写一个脚本来在 React 组件上注入 props?

所以这有点疯狂。我使用的一个 Web 应用程序是用 React 构建的,它做出了一些我不同意的设计决策。

幸运的是,设计实际上很简单,可以完全按照我想要的方式进行更改。我可以打开 Chrome React devtools 并更改分配给特定组件的道具。

但是我不想每次都手动执行此操作,这不值得。我想编写一个(超级hacky)个人javascript,我可以将它注入到页面中,它修改传递给这个组件的道具。

想知道是否有人知道从 React 外部注入 props 的简单技巧。也许有可能挂钩 React 用来响应开发工具的任何机制?

javascript reactjs react-devtools react-props react-component

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

当父组件的状态发生变化时,如何更新(重新渲染)React 中的子组件?

好的,我已经知道一种方法来做到这一点。但是,我问这个以防我重新发明轮子,因为我对 React 非常陌生。我的印象是,如果父组件通过 props 将她的状态传递给子组件而不是更新父组件的状态,那么子组件将在需要时重新渲染。但情况似乎并非如此。我设置了这个例子,

class Child extends Component {
  constructor(props) {
    super(props);
    this.state = {
      number: props.number,
    };
  }

  updateNumber(n) {
    this.setState({number: n});
  }

  render() {
    return (<h1>{this.state.number}</h1>);
  }
}

class Parent extends Component {

  constructor(props) {
    super(props);
    this.state = {
      number: -1,
    };
    this.child = React.createRef();
    setInterval(this.updateState.bind(this), 1000);
  }

  updateState() {
    console.log(this.state);
    this.setState({
      number: Math.floor((Math.random() * 10) + 1),
    });
    // this.child.current.updateNumber(this.state.number);
  }

  render() {
    return (
      <div>
        <Child ref={this.child} number={this.state.number}/>
      </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

在这个例子中,除非我明确定义一个引用并使用它来调用子级的更新函数(注释部分),否则每次更新父级的状态时都不会重新渲染子级。所以是这样吗?如果他们的父母的状态作为道具传递给他们,你是否应该手动更新你的孩子的状态(heh)或者他们应该自动更新(并因此重新渲染)。

javascript reactjs react-props react-component react-state

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

TS 错误 - 创建自定义 React 警报组件

我正在尝试创建一个自定义 React Material ui 警报组件,只需传入文本和严重性作为参数即可在不同页面上调用该组件。我正在尝试使用这个:

export default function CustomAlert(severity: string, text: string){
    <Alert style={{width:'50%'}} severity={severity}> {text}</Alert>
}
Run Code Online (Sandbox Code Playgroud)

但我在第一个严重性词上不断收到错误severity={severity}

Type 'string' is not assignable to type '"error" | "success" | "info" | "warning" | undefined'.ts(2322)
Alert.d.ts(25, 3): The expected type comes from property 'severity' which is declared here on type 'IntrinsicAttributes & AlertProps'
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?或者有其他方法来定制这个组件吗?

编辑:我仍然无法在我的其他页面中使用它:

  function StatusMessage(){
    if (isRemoved){
      return (
      <Alert style={{width:'25%'}} severity="success"> User Removed</Alert>
        )
      }
      else{
        if(errorMessage!=''){
        if (errorMessage.includes(`Couldn't find user`)){
          return (
            <div>
            {/* <Alert …
Run Code Online (Sandbox Code Playgroud)

javascript typescript reactjs material-ui react-component

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

React 何时使用全局变量而不是状态

我将从 API 加载的数据放入在函数组件外部声明的变量中。我曾想过将其置于某种状态,因为它需要通过多次渲染来保持。但我没有看到目的,因为我的代码中没有任何内容对数据的更改做出反应。

如果我继续使用这种方法在整个渲染过程中记住被动数据,这会是一种反模式吗?

var cityList;
function Component(){
    
    useEffects(async ()=>{
        if (!cityList)}{
            cityList = await loadCities();
        }
    });
    
    ...
}
Run Code Online (Sandbox Code Playgroud)

另外我知道我可以使用像useMemo(). 但我想知道这是否有问题。

最重要的是,使用这样的变量而不是 State 或 memo 的可能原因是什么

reactjs react-component

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

从自定义反应组件获取正文内容

(抱歉,如果这是一个菜鸟问题,我刚刚开始使用 React 一周,并没有在互联网上找到这个问题的答案)。

我有一个带有两个属性的 React 组件,它将这个属性之一渲染到<p>

function Item({ value, text }) {
  return (
    <div>
      {/* not relevant code here */}
      <p>{text}</p>
    <div>
  );
}
Run Code Online (Sandbox Code Playgroud)

我将其与以下代码一起使用:

<Item text="Foo" value="foo"/>
<Item text="Bar" value="bar"/>
<Item text="Baz" value="baz"/>
Run Code Online (Sandbox Code Playgroud)

但我想这样使用它:

<Item text="Foo" value="foo"/>
<Item text="Bar" value="bar"/>
<Item text="Baz" value="baz"/>
Run Code Online (Sandbox Code Playgroud)

那么如何访问 ReactItem元素的主体以及如何将其传递给属性呢?

javascript reactjs react-component

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

React/Material-UI 库本身有图像轮播组件吗?

我正在 React/Material-UI 库中搜索图像滑块(轮播)组件,但在其中找不到该组件。请帮我找到图像滑块组件。

carousel reactjs material-ui react-component

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

如何使用 Typescript 将对象传递给 ReactJS 中的自定义子组件?

客观的

我想通过useEffect()(并将它们设置为状态)获取应用程序根组件中的数据,然后将状态传递给我的自定义组件。我可以使用 JS 完成此操作,但相同的步骤不适用于 Typescript。

我的错误消息如下:

Type '{ obj: Person; }' is not assignable to type 'IntrinsicAttributes 
& Person & { children?: ReactNode; }'. Property 'obj' does not exist 
on type 'IntrinsicAttributes & Person & { children?: ReactNode; }'.TS2322
Run Code Online (Sandbox Code Playgroud)

对我来说,看起来我有一个 Person 类型的对象,我无法分配给另一种类型的 Person...

应用程序.tsx

import React, { useState, useEffect } from 'react';
import Profile from '../Profile';

export interface Person {
  name: string;
  email: string;
  dob: string;
  address: string;
  number: string;
  userName: string;
  pssw: string;
};

const initPerson: Person …
Run Code Online (Sandbox Code Playgroud)

javascript typescript reactjs react-component

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