我有一个完全用功能组件构建的 React 应用程序。我想在屏幕上呈现元素后获取元素的高度,以相应地更改其父元素的大小。
有基于类的应用程序的解决方案,但我找不到任何用于功能组件的解决方案。
我从答案中尝试了这个解决方案,但它没有运行 useEffect 钩子
这是从我的组件中提取的代码
import React, {useRef, useEffect} from 'react';
import {
MenuContainer,
GrayBox,
Wrapper
} from '../LayersMenu/LayerMenu.styles';
export const Component = ({ category, showStatistics }) => {
const grayBoxRef= useRef(null);
const wrapperRef= useRef(null);
const testRef= useRef(null);
useEffect(()=>{
const height = wrapperRef.current.offsetHeight;
console.log(height,'check');
}, [wrapperRef])
useEffect(()=>{
const height = testRef.current.offsetHeight;
console.log(height,'check2');
},[testRef]);
return (
<MenuContainer ref={testRef}>
<GrayBox ref={grayBoxRef}>
<Wrapper ref={wrapperRef} hasAnyAllowedStats={showStatistics}>
</Wrapper>
</GrayBox>
</MenuContainer>
);
};
Run Code Online (Sandbox Code Playgroud)
PS:接受的答案对我的答案不起作用,但它适用于他在答案中添加的项目,所以我猜我的项目结构有问题或不完全确定。
非常感谢回答
javascript reactjs styled-components react-functional-component
我将 React 与 Typescript 和函数式方法结合使用。
const Divider: React.FunctionComponent<CardDividerProps> = (props: CardDividerProps) => (
<div>
divider
</div>
);
const Card: React.FunctionComponent<CardProps> = (props: CardProps) => (
<div>
card
</div>
);
Card.Divider = Divider; //Property 'Divider' does not exist on type 'FunctionComponent<CardProps>'.
Run Code Online (Sandbox Code Playgroud)
如果我从卡中删除显式类型,它就会起作用。但我想用 React.FunctionComponent 来指定它......可能吗?
我想我可以创建一个类型:
type CardWithDividerComponent = {
(props: CardProps): JSX.Element;
defaultProps: CardProps;
Divider: React.FunctionComponent<CardDividerProps>;
}
Run Code Online (Sandbox Code Playgroud)
但这是唯一的解决方案吗?有什么解决办法React.FunctionComponent吗?
typescript reactjs react-tsx react-functional-component react-typescript
我是 React 的新手,当我单击View按钮时,我很难弄清楚如何返回一个新页面(一个组件)。我有一个用户表,每行都有一个查看按钮。我只能在完全相同的页面中检索数据,但我想在另一个页面中检索我的视图详细信息,其 url 上的 id,例如:http://user-details-1。有人可以帮我弄这个吗。谢谢!
这是我的视图代码/组件:
import React, { useState, useEffect } from "react";
import Form from "react-bootstrap/Form";
const ViewUserDetaiils = (props) => {
const [user, setUser] = useState(props.currentUser);
useEffect(() => {
setUser(props.currentUser);
}, [props]);
return (
<Form>
<div>
<div>
<strong>Id:</strong> {user.id}{" "}
</div>
<div>
<strong>Name:</strong> {user.name}{" "}
</div>
<div>
<strong>Contact:</strong> {user.contact}{" "}
</div>
<div>
<strong>Email:</strong> {user.email}{" "}
</div>
</div>
</Form>
);
};
export default ViewUserDetails;
Run Code Online (Sandbox Code Playgroud)
这是我的路由:
import React, { Component } from "react";
import …Run Code Online (Sandbox Code Playgroud) reactjs react-routing react-router-dom react-functional-component
我最近开始使用功能组件和react-query进行react,它运行良好,只是我不清楚如何正确组织组件。
我习惯设计组件的方式是使用一个顶级组件来执行所有数据访问并通过 props 将数据传递给它的子组件。它还将各种回调处理程序传递给子组件,以便在需要操作时,顶级组件将更新数据并将新数据传递给子组件。所以在我的例子中,所有对 useQuery()、useMutation() 的调用都驻留在顶级组件中,但这使代码变得极其混乱。但它很像包含各种子组件的页面,这些子组件仅显示数据或帮助用户与数据交互。
function Page(){
const [page, setPage] = useState(1)
const [size, setSize] = useState(10)
const persons = useQuery('persons', async ()=> await getPersons(page, size))
const addPerson = useMutation(async (args)=> {
const {id, name, desc} = args
await addPerson(id, name, description)
})
const person = useQuery('persons', async ()=> await getOnePerson(page, size), { enabled : false })
const addPersonCB = (id: number, name: string, desc: string)=> {
addPerson.mutate({id, name, desc})
}
// complex if/else logic to choose child components …Run Code Online (Sandbox Code Playgroud) typescript reactjs react-hooks react-functional-component react-query
我正在使用 React 功能组件,我只想更新状态的特定字段并像以前一样保留其他值。这是状态初始化 -
const[value, setValue] = React.useState({
a: "5",
b: "6"
});
Run Code Online (Sandbox Code Playgroud)
我只想将“a”的值更新为其他值,比如说 7(同时保留“b”的相同值)。目前我正在这样做 -
setValue(currValue => ({
...currValue,
a: "7"
}))
Run Code Online (Sandbox Code Playgroud)
这是错误的吗?如果是,正确的做法是什么?
object reactjs react-hooks react-state react-functional-component
I have the following asynchronous submitNewPatient function which is throwing @typescript-eslint/no-misused-promises error message from elint. Is it possible to adjust the function such that it removes this error?
const submitNewPatient = async (values: PatientFormValues) => {
try {
const { data: newPatient } = await axios.post<Patient>(
`${apiBaseUrl}/patients`,
values
);
dispatch({ type: "ADD_PATIENT", payload: newPatient });
closeModal();
} catch (e: unknown) {
if (axios.isAxiosError(e)) {
console.error(e?.response?.data || "Unrecognized axios error");
setError(
String(e?.response?.data?.error) || "Unrecognized axios error"
);
} else {
console.error("Unknown …Run Code Online (Sandbox Code Playgroud) typescript reactjs asynchronous-javascript axios react-functional-component
我有一个反应功能组件:
function Chat(props) {
const [messages, setMessages] = useState([]);
const inputRef = useRef();
//The socket is a module that exports the actual socket.io socket
socket.socket.on("chatMessage", (msg) => {
setMessages([...messages, msg]);
});
const inputChanged = (e) => {
if (e.key === "Enter") {
socket.sendMessage(inputRef.current.value)
.then(() => {
//do something
})
.catch(console.log);
inputRef.current.value = "";
}
};
return (
<div>
{messages.map((msg, i) => <ChatMessage key={i}>{msg}</ChatMessage>)}
<input ref={inputRef} onKeyPress={inputChanged} />
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
但是当我从 更新状态时socket.socket.on("chatMessage",出现错误
无法对已卸载的组件执行 React 状态更新
套接字告诉我需要很长时间才能响应,并且开始发生一些递归。
我应该如何从套接字事件更新组件状态?
我已经开始看到我的一些团队编写了以下代码,这让我怀疑我们是否以正确的方式做事,因为我以前从未见过这样编写的代码。
import * as React from "react";
import "./styles.css";
function UsualExample() {
return <h1>This is the standard example…</h1>
}
export default function App() {
const CustomComponent = (): JSX.Element => <h1>But can I do this?</h1>
return (
<div className="App">
<UsualExample />
<CustomComponent />
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
它似乎渲染得很好,我看不到任何直接的不利影响,但是否有一些根本原因为什么我们不应该CustomComponent从另一个组件中定义功能组件?
CodeSandbox 示例:https ://codesandbox.io/s/dreamy-mestorf-6lvtd ? file =/ src/App.tsx:0-342
我有选项列表(单选按钮),在选择每个选项时,它将显示一些输入字段以从用户那里获取值。这些值存储在“尺寸”状态中。在选项更改时,我将尺寸对象重置为未定义。但是这个值没有在输入字段中更新,而是采用旧值。
文本域:
<input value={dimensions ? dimensions[opt?.value?]: undefined}/>
关于选项更改方法:
const handleOptionChange = (e: any) => {
setDimensions(undefined);
};
Run Code Online (Sandbox Code Playgroud)
任何人都可以指导我完成这个任务吗?
提前致谢!
只是为了练习而制作一个简单的待办事项列表,我希望能够单击列表中的某个项目将其删除。我认为我已经非常接近了,但无法弄清楚如何从单击的 li 中获取某种数据以将其与我的数组进行比较。
应用程序.js
import { useState } from "react";
import "./App.css";
import Newtodo from "./NewTodo/NewTodo";
import TodoList from "./TodoList/TodoList";
let INITIAL_TODOS = [
{ id: "e1", title: "Set up meeting", date: new Date(2021, 0, 14), index: 0 },
{
id: "e2",
title: "Doctor appointment",
date: new Date(2021, 2, 14),
index: 1,
},
{ id: "e3", title: "Work on project", date: new Date(2021, 1, 22), index: 2 },
{ id: "e4", title: "Update resume", date: new Date(2021, 6, 14), index: …Run Code Online (Sandbox Code Playgroud) react-functional-component ×10
reactjs ×9
javascript ×4
react-hooks ×3
typescript ×3
axios ×1
jsx ×1
list ×1
object ×1
onchange ×1
react-query ×1
react-state ×1
react-tsx ×1
socket.io ×1