标签: react-class-based-component

React super(props) 被弃用了吗?

我一直使用类似的东西

class MyComponent extends React.Component {
    constructor(props) {
        super(props)
        
        this.state = {
            var1 : undefined,
            var2 : 'etc...',
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是今天我注意到在 VS Code 中工作时有一条划线super(props),这是以前从未有过的!?

在此处输入图片说明 发生了什么变化?(弹出窗口中文档的链接不是很有帮助)

reactjs visual-studio-code react-class-based-component

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

如何在 Typescript 中正确键入 React ErrorBoundary 类组件?

这是我目前关于如何ErrorBoundary在 Typescript 中正确键入 React类组件的尝试:

import React from "react";
import ErrorPage from "./ErrorPage";
import type { Store } from "redux";   // I'M PASSING THE REDUX STORE AS A CUSTOM PROP

interface Props {
  store: Store         // THIS IS A CUSTOM PROP THAT I'M PASSING
}

interface State {      // IS THIS THE CORRECT TYPE FOR THE state ?
  hasError: boolean
}

class ErrorBoundary extends React.Component<Props,State> {
  
  constructor(props: Props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error): …
Run Code Online (Sandbox Code Playgroud)

typescript reactjs typescript-typings react-error-boundary react-class-based-component

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

ApolloProvider 客户端 - 如何从 React 类组件访问?

我正在构建 React App 并且需要使用类组件。

我在index.js 中设置了一个ApolloClient,它将客户端传递给ApolloProvider。如何在我的应用程序组件(类组件)中访问它?有可能吗?我还设置了 Redux 并使用 connect 将状态映射到 props (我考虑过使用export default withApollo(App),但后来我失去了使用 connect() 映射到 props 的状态)。

有人可以帮助/解释如何使用 React 类组件正确实现 apollo-client 吗?我应该在每个类组件中创建新的 ApolloClient 吗?

索引.js

const apolloClient = new ApolloClient({
  uri: "http://localhost:4000/",
  cache: new InMemoryCache(),
});

...

<ApolloProvider client={apolloClient}>
   <App />
</ApolloProvider>
Run Code Online (Sandbox Code Playgroud)

应用程序.js

class App extends Component {
  render() {
...
  }
}

const mapStateToProps = (state) => {
  return {
     ...
  };
};

export default connect(mapStateToProps)(App);
Run Code Online (Sandbox Code Playgroud)

reactjs apollo-client react-class-based-component

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

如何在reactjs中映射图像

所以在 Reactjs 类组件中,我的状态有一个数组,如下所示:

myArray: [
   { number: 1, title: 'Users', image: '../../../assets/images/website/homepage/users.png' },
   { number: 2, title: 'Clients', image: '../../../assets/images/website/homepage/clients.png' },
   { number: 3, title: 'Admin', image: '../../../assets/images/website/homepage/admins.png' },
]
Run Code Online (Sandbox Code Playgroud)

我这样映射数组:

{this.state.myArray.map((item, index) => (
   <Box key={index} className="col-sm-12">
      <img src={ item.image } className="img-fluid" alt={item.title} />
      <Typography variant="h4">{item.number}</Typography>
   </Box>
))}
Run Code Online (Sandbox Code Playgroud)

现在,一切正常,除了图像不显示,我真的不明白我哪里出错了。

请注意,如果我使用 require 方法直接将图像链接之一复制到 src 内,则它可以工作。请帮忙。

jsx reactjs react-class-based-component

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

使用 React 处理的 onClick 创建锚点

我有一个 React 组件,它根据状态呈现<ul>和插入<li>元素。

class SimpleComponent extends React.Component {
  constructor(props) {
    this.state = { menu_items: [name: "First", id: 10] }
    this.clickMenu = this.clickMenu.bind(this)
  }
  generateLinks() {
    let to_return='';
    for (var i=0;i<this.state.menu_items.length; i++) {
      to_return = to_return + `<li><a onclick={clickMenu}> ${this.state.menu_item[i]['name']} </a></li>`
     }
     return to_return;
   }
   clickMenu(e) {
     console.log(e.target)
   }
   render() {
     return(
       <ul dangerouslySetInnerHTML={this.generateLinks()}></ul>
     )
   }
}
Run Code Online (Sandbox Code Playgroud)

当我单击 Anchor 时,控制台显示 Uncaught ReferenceError: clickMenu not defined。我尝试使用 this.clickMenu 代替,但没有任何反应。我注意到渲染的锚点看起来像:

<a onclick="{menuClick}">
Run Code Online (Sandbox Code Playgroud)

有没有办法创建这些锚元素让 React 获取 onClick 定义而不是将它们传递给浏览器进行解释?

javascript anchor onclick reactjs react-class-based-component

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

节点步骤的边缘未在反应流渲染器中渲染

我试图将 data.js 文件中的步骤显示为节点,并尝试连接这些边。但边缘仅可见。在页面中。我使用了 [react-flow-renderer] 包1

当我刷新页面时,边缘甚至一秒钟都看不见。

我的反应组件

import React, { Component } from 'react'
import data from '../data'
import ReactFlow, {addEdge} from 'react-flow-renderer'


export class Pro2 extends Component {
    constructor() {
        super()
        this.state = {
            steps:data.map((step, index) => ({ id: step.id, data: {label: step["step-name"] }, position: {x: 500, y:100 * (index + 1)}})),
            tasks:[],
            sedges: data.slice(0, data.length - 1).map((step, index) => ({id:"e"+step.id+data[index+1].id, source: step.id, target: data[index+1].id, animated: true}))
        }
        console.log(this.state.steps, this.state.sedges)
        this.handleChange = this.handleChange.bind(this)
    }

    handleChange(t) {
        //console.log("clicked...............clicked …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-class-based-component react-flow

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

无法访问 Ant Modal 中的 this.setState 或 this.state 确认确定/取消功能

我在访问onCancel/onOk 函数时this.state遇到问题。this.setState我想修改确认或取消弹出模态后的状态。如果有人有不同的方法,您的指导将会有所帮助。

import React from 'react';
import { Button, Modal } from 'antd';

class ExampleClass extends React.Component {
  constructor() {
    super();

    this.state = {
      bankInfo: 100,
    };
  }

  onButtonClicked() {
    this.setState({ bankInfo: 200 });            // works fine
    Modal.confirm({
      title: 'Are you sure delete this item?',
      okType: 'danger',
      onOk() {
        this.setState({ bankInfo: 300 }); // Uncaught TypeError: Cannot read property 'setState' of undefined
      },
      onCancel() {
        this.setState({ bankInfo: 400 }); // Uncaught TypeError: Cannot read property 'setState' …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs antd ant-design-pro react-class-based-component

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

如何在类组件中使用 Context API

我正在做一个非常大的翻译项目。我使用Formspree来处理表单。我也想翻译一下。

这是Formspree给出的代码:

import React, { useContext } from "react";
import { LanguageContext } from "../../../../App";
import './Form.css';

export default class MyForm extends React.Component {
    constructor(props) {
        super(props);
        this.submitForm = this.submitForm.bind(this);
        this.state = {
            status: ""
        };
    }
    
    render() {
        const { status } = this.state;
        return (
            <form
                onSubmit={this.submitForm}
                action="https://formspree.io/f/********"
                method="POST"
            >
                {/* <!-- add your custom form HTML here --> */}
                <div className="container">
                    <label style={{ color: 'black', fontSize: '18px' }}>Name <span style={{ color: '#f14b4d' }}>(Required)</span>:</label>
                    <input …
Run Code Online (Sandbox Code Playgroud)

reactjs react-context react-class-based-component

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

更改值后反应组件未更新

在 ReactJS 中,我正在编写一个无状态组件;
因为我读过避免不必要的状态是最佳实践。

该组件代表一个输入字段,当输入框包含一个值时,它会执行一个函数。

    export const InputField = (props) => {
      
      const InputFieldContentsChanged = (event) => {
        props.onChange(event.target.value);
      };

      return (
        <div data-component="input-field"
          className={(props.value !== "" ? "value": "")}>
          <input type={props.type} value={props.value} onChange={InputFieldContentsChanged} />
          <span className="bar"></span>
          <label>{props.label}</label>
        </div>
      );
    };

    InputField.PropTypes = {
      type: PropTypes.oneOf([ "text", "password" ]).isRequired,
      label: PropTypes.string.isRequired,
      value: PropTypes.string,
      onChange: PropTypes.func.isRequired
    }
Run Code Online (Sandbox Code Playgroud)

现在,我创建了另一个组件,它只是测试上述组件的示例。如下所示:

    export const SampleComponent = (props) => {
      
      let componentUsername = "";
      
      const onUsernameChanged = (username) => {
        componentUsername = username;
      };
      
      return ( …
Run Code Online (Sandbox Code Playgroud)

reactjs react-hooks react-state react-functional-component react-class-based-component

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

将反应类组件转换为功能组件,渲染完美但功能丢失?

我正在制作一个小型音频播放器应用程序并尝试将我的反应类组件转换为功能组件。

类组件的原始代码在这里:

class Player extends React.Component {

    constructor(){
    super()

    this.state = {
        tracks: [
          {title: "first track", data: track1},
          {title: "second track", data: track2},
          {title: "third track", data: track3},
        ],
        currentTrack: 0,
    }

    }

     changeData(trackIndex){
      this.setState({currentTrack: trackIndex})
    }
  
    render(){
        return <div style={{color: this.props.color}}>
            <h1>Player</h1>
           <AudioPlayer
            src= {this.state.tracks[this.state.currentTrack].data}
            />
            <div style={{color: "green"}}>
                <ul>
                    {this.state.tracks.map((trackElem, index) => (
                       <li onClick={()=> this.changeData(index)}>{trackElem.title}</li>
                    ))}
                </ul>
            </div>
        </div>
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试了以下转换:

const Player2 = () => {

   const Items = [
          {title: "first track", data: …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-hooks react-class-based-component

0
推荐指数
1
解决办法
29
查看次数