小编You*_*mar的帖子

使用 React 时获取 SyntheticBaseEvent 对象而不是简单的 Event

我有这个非常简单的 React 代码:

\n
const onSelectTournament = (e) => {\n    console.log(e);\n};\n
Run Code Online (Sandbox Code Playgroud)\n

还有这个 HTML:

\n
<div onClick={onSelectTournament}></div>\n
Run Code Online (Sandbox Code Playgroud)\n

但在控制台上,我没有获取对象,而是Event得到了这个地狱对象:

\n
    SyntheticBaseEvent {_reactName: 'onClick', _targetInst: null, type: 'click', nativeEvent: PointerEvent, target: div.tournamentsBoxDescription, \xe2\x80\xa6}\naltKey: false\nbubbles: true\nbutton: 0\nbuttons: 0\ncancelable: true\nclientX: 382\nclientY: 269\nctrlKey: false\ncurrentTarget: null\ndefaultPrevented: false\ndetail: 1\neventPhase: 3\ngetModifierState: \xc6\x92 modifierStateGetter(keyArg)\nisDefaultPrevented: \xc6\x92 functionThatReturnsFalse()\nisPropagationStopped: \xc6\x92 functionThatReturnsFalse()\nisTrusted: true\nmetaKey: false\nmovementX: 0\nmovementY: 0\nnativeEvent: PointerEvent {isTrusted: true, delegateTarget: document, pointerId: 1, width: 1, height: 1, \xe2\x80\xa6}\npageX: 382\npageY: 269\nrelatedTarget: null\nscreenX: 382\nscreenY: 373\nshiftKey: false\ntarget: div.tournamentsBoxDescription\ntimeStamp: 102788.7999997139\ntype: "click"\nview: Window {window: Window, …
Run Code Online (Sandbox Code Playgroud)

html javascript reactjs

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

获取 ReferenceError:即使添加“使用客户端”后,本地存储也未定义

我有一个简单的app/components/organisms/Cookies.tsx模态窗口组件,我将其导入到app/page.tsx. 我已'use client'在组件顶部添加了指令,但由于某种原因,我不断收到:

ReferenceError:本地存储未定义

在此输入图像描述

我的代码Cookies.tsx

'use client';
import { useState } from 'react';

const Cookies = () => {
  const localStorageCookies = localStorage.getItem('cookies-accepted');
  const [cookiesAccepted, setCookiesStatus] = useState<boolean>(!!localStorageCookies);

  const acceptCookies = () => {
    localStorage.setItem('cookies-accepted', 'true');
    setCookiesStatus(true);
  }
  
  return (
    <>
      {!cookiesAccepted && (
        <section className="fixed max-w-md p-4 mx-auto bg-white border border-gray-200 left-12 bottom-16  rounded-2xl z-20">
          <h2 className="font-semibold text-gray-800 "> Cookie Notice</h2>

          <p className="mt-4 text-sm text-gray-600">
            We use cookies to ensure that …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs server-side-rendering next.js

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

错误:Node Sass 尚不支持您当前的环境

当我使用 command 在 Fedora 32 中启动 React 项目时yarn start,它显示如下错误:

\n
./src/style/base.scss (./node_modules/css-loader/dist/cjs.js??ref--6-oneOf-5-1!./node_modules/postcss-loader/src??postcss!./node_modules/resolve-url-loader??ref--6-oneOf-5-3!./node_modules/sass-loader/dist/cjs.js??ref--6-oneOf-5-4!./src/style/base.scss)\nError: Node Sass does not yet support your current environment: Linux 64-bit with Unsupported runtime (93)\nFor more information on which environments are supported please see:\nhttps://github.com/sass/node-sass/releases/tag/v4.14.1\n
Run Code Online (Sandbox Code Playgroud)\n

我当前的节点版本是:

\n
[dolphin@MiWiFi-R4CM-srv]~/Documents/GitHub/react-admin% nvm list\n        v8.17.0\n       v10.24.1\n->     v16.13.0\n        v17.2.0\n         system\ndefault -> 8 (-> v8.17.0)\n
Run Code Online (Sandbox Code Playgroud)\n

我尝试了不同版本的节点但没有解决这个问题,为什么会发生这种情况?我应该怎么做才能解决这个问题?我没有node-sass在 中找到任何包依赖项package.json,这是 package.json 文件:

\n
{\n    "name": "react-admin",\n    "version": "0.1.0",\n    "private": true,\n    "dependencies": {\n        "@ant-design/compatible": "1.0.8",\n        "animate.css": "^3.7.2",\n        "antd": "^4.0.0",\n        "axios": "^0.19.0",\n …
Run Code Online (Sandbox Code Playgroud)

javascript node.js reactjs node-sass

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

为什么 Webpack 5 没有 CSS 文件输出?

到处搜索了好几天,我仍然无法理解为什么我最新的尝试也不起作用。

为什么 dist 文件夹中没有 CSS 文件?

现在,我正在将样式导入到一个.js文件中,该文件稍后会导入到我的应用程序入口点中,但仍然什么也没有。

webpack.config.js

const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HTMLWebpackPlugin = require('html-webpack-plugin');

const path = require('path');

const paths = {
  src: path.resolve(__dirname, 'src'),
  dist: path.resolve(__dirname, 'dist'),
};

module.exports = {
  entry: 'index.js',
  mode: 'production',
  cache: false,
  output: {
    path: paths.dist,
    filename: 'index.js',
  },
  module: {
    rules: [
      {
        test: /\.s[ac]ss$/i,
        use: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              sourceMap: true,
            },
          },
          {
            loader: …
Run Code Online (Sandbox Code Playgroud)

javascript css webpack webpack-5

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

React Native &amp; Expo,如何控制闪屏?

我正在使用博览会中的内置启动屏幕,您可以将其添加到app.json一个简单的测试应用程序中。但是我注意到我的开始屏幕在显示我添加的资源之前以默认模式闪烁 1 毫秒AsyncStorage

我尝试过使用世博会的启动画面包,但我发现它有点令人困惑。有没有一种相当简单的方法来添加我的App.js这个逻辑:

显示启动屏幕,当加载所有资源时,加载此设置(使用我的上下文和屏幕),或者只是增加博览会启动屏幕中构建的加载时间(因为我假设它会加载正在获取的资源?)。

const App = () => {

  const [selectedTheme, setSelectedTheme] = useState(themes.light)

  const changeTheme = async () =>{
    try {
      const theme = await AsyncStorage.getItem("MyTheme")
      if (theme === "dark"){
      setSelectedTheme(themes.nightSky)} 
      else if (theme === "light") {
        setSelectedTheme(themes.arctic)
        }
    } catch (err) {alert(err)}
  }
  
  useEffect(()=> {
    changeTheme()
  },[])


  return (
    <ThemeContext.Provider value={{selectedTheme, changeTheme}}>
         <NavigationContainer>
            <Stack.Navigator screenOptions={{headerShown:false, presentation: 'modal'}}>
              <Stack.Screen name="Home" component={home}/>
            </Stack.Navigator>
          </NavigationContainer>
    </ThemeContext.Provider>

  );
};
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-native expo

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

React Navigation,如何隐藏后退按钮标题?

我正在使用 React Native 构建 Android 和 iOS 应用程序。我用来react-navigation在屏幕之间导航。

问题在于 iOS 上的导航与 Android 上的导航不同(下图)。我希望它们都像 Android 上一样,那么如何在 iOS 上隐藏“搜索汽车”呢?

在此输入图像描述

我已将导航选项设置如下:

Screen.navigationOptions = () => {

    const title = 'Search location';

    return {
        headerTitleStyle: {
            fontSize: 18,
            color: styles.headerTitle.color,
            paddingTop: 5,
            height: 40
        },
        headerStyle: {
            backgroundColor: '#fdfdfd'
        },
        title
    };
};
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-native react-navigation

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

React 和 TypeScript,出现“Type预期”错误

我正在将 React 组件从 JS 转换为 Typescript (*.ts)。它给出了“预期类型”下方的错误。我该如何解决这个问题?

const SisenseDashboard = () => {

  const sisenseRef = React.useRef(null);

  return (
    <>
      <Box
        display="flex"
        flexDirection="column"
        alignItems="center"
        marginBottom={2}
      >
        <h2>In-App Reporting</h2>
      </Box>
      <Box
        ref={sisenseRef}
        id="sisense-container"
        className="sisense-demo"
      ></Box>
    </>
  );
};
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

javascript typescript reactjs

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

如何在React中通过API请求更新数据后的状态?

我有一个小问题。我在一个运行良好的组件中获取数据:

const [item, setItem] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setLoading(true);
    fetch("https://api/products")
      .then((response) => response.json())
      .then((data) => setItem(data))
      .finally(() => setLoading(false));
  }, []);

Run Code Online (Sandbox Code Playgroud)

然后我将这个 POST 放在不同的组件中:

const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      await fetch("https://api/products", {
        method: "POST",
        headers: { admin: "true", "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
    } catch (error) {
      console.log("error");
    }
  };
Run Code Online (Sandbox Code Playgroud)

使用POST后,如何在不重新加载网页的情况下获取第一个组件的新数据?

javascript reactjs

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

类型“IntrinsicAttributes &amp; Props”上不存在属性“...”

我的应用程序中有一个<InputField>组件,其属性的类型定义如下:

interface InputFieldProps extends React.HTMLAttributes<HTMLInputElement> {
  customProp: string;
}
Run Code Online (Sandbox Code Playgroud)

我的组件如下所示:

const InputField: React.FC<InputFieldProps> = ({ customProp, ...htmlProps }) => {

  return (
    <input {...htmlProps} />
  );
};
Run Code Online (Sandbox Code Playgroud)

我希望现在可以将 propdisabled或传递required给该组件,因为这些属性是 HTMLInputElement 类型定义的一部分。但是,我收到错误:

类型“IntrinsicAttributes & Props”上不存在属性“disabled”

我尝试通过残疾人disabled={true}以及但disabled没有成功。不过,我可以placeholder作为道具通过。因此 HTMLInputElement 类型定义中的某些属性似乎有效,而其他属性则无效。

html javascript typescript reactjs

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

查询数据不能是未定义的。请确保从查询函数中返回除未定义之外的值

我使用 useQuery 钩子向 graphql 端点发送请求,我使用react.js 和 next.js。此请求是为了在我的网站上显示项目列表。当我在 Chrome 浏览器的检查工具中检查网络选项卡时,请求正常,显示响应数据没有问题,但在控制台中,我收到以下错误:

查询数据不能是未定义的。请确保从查询函数中返回除 undefined 以外的值。受影响的查询键:[“newProjects”]

错误:在解析时 (retryer.mjs?bd96:54:1) 处的 Object.onSuccess (query.mjs?b194:316:1) 处未定义

我创建了一个钩子来发出请求并获取另一个组件中的数据:

import { useQuery } from "@tanstack/react-query";
import { request, gql } from 'graphql-request'
import { endpointProjects } from "../settings";

export function useAllProjects() {

  return useQuery(
    ['newProjects'],
    async () => {
      const data = await request(
        endpointProjects.newProjects,
        gql`
        query MyQuery {
            newProjects(orderBy: blockTimestamp, orderDirection: desc, first: 10, skip: 0) {
              id
              project
              name
              symbol
              uri
              blockNumber
              blockTimestamp
              transactionHash
            }
          }
      `,
      ) …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs graphql next.js react-query

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