我现在有一个函数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)
这是班级 …
使用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,因为没有道具似乎改变了?
我有这两个组成部分:
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) 我有一个不同大小的图像列表.
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) 我正在使用TypeScript和React.我已经定义了我的AppContainer.tsx组件,将其导出为默认值.我在文件app.ts中使用ReactDOM它来生存它以将其呈现给目标dom元素.但我收到以下错误(见图).有关更多信息和GitHub repo的链接,请阅读以下内容.
问题:我在做什么或者解释是什么?从所有代码示例我看到这应该工作 - 但也许(显然)我错过了一些东西.以下是更多信息和完整GitHub仓库的链接.
/// <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) 这一直是我遇到的webpack最奇怪的问题之一......
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) 在我的反应应用程序中,我尝试使用 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 事件?
在为这个例子添加样式组件之后,我们注意到当我们只修改了一个状态项时,我们的列表组件会更新所有内容.
添加/删除单个条目时,列表呈现突出显示(来自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重新呈现状态中的修改对象?
将我的 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) 我有一个组件,它调用 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) react-dom ×10
reactjs ×10
javascript ×2
babel-loader ×1
classname ×1
components ×1
cordova ×1
performance ×1
tsx ×1
typescript ×1
webpack-2 ×1