标签: react-dom

如何在ReactJS中检查事件目标的类名?

在此输入图像描述

我现在有一个函数handleRightClick(e),当我右键单击容器时将调用该函数.在容器内部,有几个Items,我希望只有当我右键单击其中一个时才会显示菜单Item.

export default class ProjectContainer extends React.Component {
    ...
    handleRightClick(e) {
        console.log(e.target.name); // I want to check the event target whether is `Item` Class.
        this.refs.rightClickMenu.reShow(e.clientX, e.clientY); // This will open the right click menu.
    }
    ...
    render() {
        return (
            <div style={styles.root} onContextMenu={this.handleRightClick} onClick={this.handleLeftClick}>
                <Item /><Item /><Item /><Item /><Item /><Item /><Item />
                <RightClickMenuForProjectItem ref='rightClickMenu'/>
            </div>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我console.log(e),我在Chrome控制台中得到这个:

> Object {dispatchConfig: Object, _targetInst: ReactDOMComponent, _dispatchInstances: ReactDOMComponent, nativeEvent: MouseEvent, type: "contextmenu"…}
Run Code Online (Sandbox Code Playgroud)

这是班级 …

classname javascript-events reactjs react-dom

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

当Component有子节点时,React.PureComponent不起作用?

使用PureComponent来改善React中的渲染性似乎是一种常见的技术.但是,使用具有子项作为道具的PureComponent时似乎并非如此.

class App extends React.PureComponent {
  render() {
    console.log('re-render') 
    return <div>{this.props.children}</div>
  }
}

const render = () => {
  ReactDOM.render(
    <App>
      <div />
    </App>,
    document.getElementById('app')
  )
  setTimeout(render, 1000)
}

render()
Run Code Online (Sandbox Code Playgroud)

结果是控制台每1秒保持记录"重新渲染".似乎children(<div />)是上面App组件的唯一支柱并且永远不会改变,为什么App仍然会被重新渲染?

注意:如果有任何混淆,问题是相同的,为什么上面的PureComponent的SCU(shouldComponentUpdate)钩子返回true,因为没有道具似乎改变了?

performance components reactjs react-dom

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

如何使用React.createRef()API从Class Component ref获取DOM节点

我有这两个组成部分:

import { findDOMNode } from 'react-dom';

class Items extends Component {
    constructor(props) {
        super(props);
        this.ref = React.createRef();
        this.selectedItemRef = React.createRef();
    }

    componentDidMount() {
        if (this.props.selectedItem) {
            this.scrollToItem();
        }
    }

    componentWillReceiveProps(nextProps) {
        if (this.props.selectedItem !== nextProps.selectedItem) {
            this.scrollToItem();
        }
    }

    scrollToItem() {
        const itemsRef = this.ref.current;
        const itemRef = findDOMNode(this.selectedItemRef.current);

        // Do scroll stuff here
    }

    render() {
        return (
            <div ref={this.ref}>
                {this.props.items.map((item, index) => {
                    const itemProps = {
                        onClick: () => this.props.setSelectedItem(item.id)
                    };

                    if (item.id === this.props.selectedItem) { …
Run Code Online (Sandbox Code Playgroud)

reactjs react-dom

8
推荐指数
1
解决办法
1149
查看次数

在渲染之前查找反应组件或图像的大小

我有一个不同大小的图像列表.

images = ['https://example.com/1.jpg','https://example.com/2.jpg', ... ]
Run Code Online (Sandbox Code Playgroud)

我想在渲染之前得到一个高度数组.然后,我将仅基于scrollHeight渲染应该在视口中的图像.例如使用React Infinte

我可以轻松地做出反应组件之外的事情

let imgHeights =  images.map(imgUrl => {
    var img  = new Image()
    img.src = imgUrl
    return img.height;
})
Run Code Online (Sandbox Code Playgroud)

new image()由于它取决于DOM,因此不起作用.

我的React组件渲染方法如下所示.

var ImageList = (images) => {
     let buildImageList = images.map(imgUrl => {
         return <img src= {imgUrl}></img>
     })

     let imgHeights = images.map(imgUrl => {
         let img = new Image()
         img.src = imgUrl
         return img.height //this doesn't work 
     })

     return (
         <Infinte elemetHeight = {imgHeights} onInfiniteLoad ={buildImageList} />
     ) 
} …
Run Code Online (Sandbox Code Playgroud)

reactjs react-dom

7
推荐指数
1
解决办法
3041
查看次数

TypeScript和ReactDOM.render方法不接受组件

TL; DR

我正在使用TypeScript和React.我已经定义了我的AppContainer.tsx组件,将其导出为默认值.我在文件app.ts中使用ReactDOM它来生存它以将其呈现给目标dom元素.但我收到以下错误(见图).有关更多信息和GitHub repo的链接,请阅读以下内容.

在此输入图像描述

问题:我在做什么或者解释是什么?从所有代码示例我看到这应该工作 - 但也许(显然)我错过了一些东西.以下是更多信息和完整GitHub仓库的链接.


环境

文件'/components/AppContainer.tsx'

/// <reference path="../../../typings/index.d.ts" />

// Top level application component

/*------------------------------------------------------------------------------------*/
/** IMPORTS **/
import * as React from 'react';
import { Component } from 'react';
/*------------------------------------------------------------------------------------*/
/*///*/

/*------------------------------------------------------------------------------------*/
/** COMPONENT **/
export default class AppContainer extends React.Component<{}, {}> {    
    render() {
        return ( <div /> );
    }    
}        
/*------------------------------------------------------------------------------------*/
/*///*/ …
Run Code Online (Sandbox Code Playgroud)

typescript reactjs tsx react-dom typescript-typings

7
推荐指数
1
解决办法
5997
查看次数

react-dom吹出webpack捆绑大小MASSIVELY

这一直是我遇到的webpack最奇怪的问题之一......

查看此捆绑细分: 在此输入图像描述 反应116.01KB - 足够公平

react-dom 533.24KB - 认真的WTF

我认为它可能是我的依赖项中的损坏,但nuking node_modules并重新安装没有任何影响.我想这与webpack捆绑它的方式有关,但是我迷失了想法.我正在处理.js进口的方式是相当的股票标准.

// webpack.config.js
const path = require('path');
// const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const Dashboard = require('webpack-dashboard');
const DashboardPlugin = require('webpack-dashboard/plugin');

const dashboard = new Dashboard();

module.exports = {
  context: path.join(__dirname, 'src'),
  entry: {
    bundle: './index.js',
  },
  output: {
    filename: 'bundle.js',
    path: path.join(__dirname, 'build'),
  },
  module: {
    rules: [
      {
        test: /\.html$/,
        use: 'file-loader?name=[name].[ext]',
      },
      {
        test: /.scss$/,
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: [
            'css-loader',
            'postcss-loader',
          ], …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-dom webpack-2 babel-loader

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

反应组件中的 onDeviceReady 事件侦听器

在我的反应应用程序中,我尝试使用 Cordova 插件(cordovo-plugin-device)来获取用户的设备版本,如下所示

class LogoHeader extends React.Component {
  componentDidMount () {
    window.addEventListener('deviceready', this.onDeviceReady)
  }
  onDeviceReady () {
    console.log(device.cordova)
  }
  render () {
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)

但出于某种原因,该deviceready事件永远不会被触发。我错过了什么吗?有没有更好的方法在 react 中监听 DOM 事件?

cordova reactjs cordova-plugins react-dom

7
推荐指数
1
解决办法
782
查看次数

使用样式组件防止Component/PureComponent在状态更改后重新呈现所有项目

在为这个例子添加样式组件之后,我们注意到当我们只修改了一个状态项时,我们的列表组件会更新所有内容.

添加/删除单个条目时,列表呈现突出显示(来自React dev-tools)过多.删除/添加一个项目,然后突出显示所有项目.

在此输入图像描述

代码示例

以下是右侧列表组件(CategorizedList.js)的示例

import styled from "styled-components";

const Item = styled.li`
  color: #444;
`;

class CategorizedList extends PureComponent {
  render() {
    return (
      <div>
        {this.props.categories.map(category => (
          <ul>
            <li key={this.props.catStrings[category]}>
              {this.props.catStrings[category]}
            </li>
            <ul>
              {this.props.items.map((item, index) =>
                item.category === category ? (
                  <div key={item.label + index}>
                    <Item>{item.label}</Item>
                  </div>
                ) : null
              )}
            </ul>
          </ul>
        ))}
      </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

偏爱

我更喜欢使用PureComponent,以便shouldComponentUpdate() 自动处理.

我们如何才能确保只items重新呈现状态中的修改对象?

reactjs react-dom styled-components

7
推荐指数
1
解决办法
915
查看次数

GET 请求返回 index.html doc 而不是 json 数据

将我的 mern 应用程序部署到 Heroku 后,GET主页上的请求('http://localhost:8000/post/')现在返回index.html而不是json data从请求中返回。我正在获取200 status代码,但响应是html. 但是,它在本地运行良好。
除了这个请求之外,所有其他请求都在工作。每当我认为我已经修复它时,Heroku 会在同一条路线上显示 json 数据而不是 UI。我假设这些问题是相关的。

我该如何解决这个问题?谢谢!

路由/控制器 - 列出帖子

router.get('/', (list)) 

exports.list = (req, res) => {
  const sort = { title: 1 };
  Post.find()
    .sort(sort)
    .then((posts) => res.json(posts))
    .catch((err) => res.status(400).json("Error: " + err));
};
Run Code Online (Sandbox Code Playgroud)

服务器.js

require("dotenv").config();

// import routes
...
const app = express();

// connect db - first arg is url (specified in .env)
const url = …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-dom

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

如何正确卸载使用createRoot创建的东西?

我有一个组件,它调用 React 18createRoot来经常在其中渲染一些内容。我的问题是,如果我尝试删除它,则会unmount触发componentWillUnmount警告:Warning: Attempted to synchronously unmount a root while React was already rendering. React cannot finish unmounting the root until the current render has completed, which may lead to a race condition.

如何正确地做到这一点?当我使用 .React 17 时,这段代码没有抛出任何警告ReactDOM.render()。这是一个最小的例子:

import React from "react";
import { createRoot } from "react-dom/client";

class Example extends React.Component {
  componentWillUnmount() {
    if (this._root) {
      // This is causing the warning
      this._root.unmount();
    }
  }
  render() {
    return (
      <div …
Run Code Online (Sandbox Code Playgroud)

reactjs react-dom

7
推荐指数
1
解决办法
1716
查看次数