我有一个简单的反应组件,我相信有一个受控输入的形式:
import React from 'react';
export default class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = {}
}
render() {
return (
<form className="add-support-staff-form">
<input name="name" type="text" value={this.state.name} onChange={this.onFieldChange('name').bind(this)}/>
</form>
)
}
onFieldChange(fieldName) {
return function (event) {
this.setState({[fieldName]: event.target.value});
}
}
}
export default MyForm;
Run Code Online (Sandbox Code Playgroud)
当我运行我的应用程序时,我收到以下警告:
警告:MyForm正在更改要控制的类型文本的不受控制的输入.输入元素不应从不受控制切换到受控制(或反之亦然).决定在组件的使用寿命期间使用受控或不受控制的输入元素
我相信我的输入是有控制的,因为它有一个值.我想知道我做错了什么?
我正在使用React 15.1.0
我正在尝试使用一个函数作为组件内的道具,而这个组件是另一个组件的子组件。但该功能不起作用。?我能知道为什么吗。这是我在控制台中收到的警告。
警告:在 StrictMode 中不推荐使用 findDOMNode。findDOMNode 传递了一个位于 StrictMode 内的 Transition 实例。相反,直接向要引用的元素添加 ref
这是我的代码
class Todo extends Component {
state = {
show: false,
editTodo: {
id: "",
title: "",
isCompleted: false
}
}
handleClose = () => {
this.setState({ show: false })
}
handleShow = () => {
this.setState({ show: true })
}
getStyle () {
return {
background: '#f4f4f4',
padding: '10px',
borderBottom: '1px #ccc dotted',
textDecoration: this.props.todo.isCompleted ? 'line-through'
: 'none'
}
}
//this method checks for changes in the …Run Code Online (Sandbox Code Playgroud) 我有一家简单的商店
interface CartState {
cart: { [id: string]: CartDto };
addItem: ({ id, image, name, price }: Omit<CartDto, "quantity">) => void;
removeItem: (id: string) => void;
reset: () => void;
}
export const useCart = create<CartState>((set, get) => ({
cart: {},
addItem: ({ id, image, name, price }) => {
set(() => {
const cart = get().cart;
if (!cart[id]) {
cart[id] = {
id,
image,
name,
price,
quantity: 0
};
}
cart[id].quantity += 1;
return { cart };
});
}, …Run Code Online (Sandbox Code Playgroud) 我正在第一次渲染时测试组合框,组合框的初始值未定义。然后使用查询参数和 useEffect 组件找到相关选项并为其设置值状态。
const Component = () => {
[value, setValue] = useState(undefined);
useEffect(() => {
setValue("hello")
}, [])
return(
<Combobox value={value}/>
)
}
Run Code Online (Sandbox Code Playgroud)
it("should render with value as hello", () => {
const {getByText} = render(<Component/>)
const text = getByText("hello")
})
Run Code Online (Sandbox Code Playgroud)
该测试套件抛出此错误:
TestingLibraryElementError: Unable to find an element with the text: Photobug. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your …Run Code Online (Sandbox Code Playgroud) javascript reactjs react-testing-library react-hooks react-state
我是 React 与 Typescript 的新手,我收到一条错误消息:
没有重载匹配这个调用。重载 1 of 2,'(props: Readonly<{}>): IndexPage',出现以下错误。
输入 '{ 注释:{ 1: { _id: number; 标题:字符串;正文:字符串;更新时间:日期;}; }; }' 不可分配到类型 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{}> & Readonly<{ children?: ReactNode; }>'。类型“IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{}> & Readonly<{ children?: ReactNode;”上不存在属性“notes” }>'。重载 2 of 2, '(props: {}, context?: any): IndexPage',出现以下错误。输入 '{ 注释:{ 1: { _id: number; 标题:字符串;正文:字符串;更新时间:日期;}; }; }' 不可分配到类型 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{}> & Readonly<{ children?: ReactNode; }>'。属性“注释” 不存在于类型 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{}> & Readonly<{ children?: ReactNode; …
我正在开发一个库Next.js 应用程序。出于此问题的目的,我的应用程序中有两个页面:列出所有书籍的BooksPage和呈现书籍详细信息的BookPage 。就组件而言,我有一个<Books />组件可以<Book />为我的图书馆数据库中的每本书呈现一个组件。
这是我的组件:
图书.js:
function Books({ books }) {
return (
<>
{books.map(book => (
<Book key={book.id} book={book} />
))}
</>
);
}
Run Code Online (Sandbox Code Playgroud)
书.js:
class Book extends React.Component {
constructor(props, context) {
super(props, context);
this.state = { liked: false };
}
like = () => {
this.setState({ liked: this.state.liked ? false : true })
};
render() {
return (
<>
<Link href={`/books/${book.slug}`}>
<a>{book.title}</a>
</Link>
<Button …Run Code Online (Sandbox Code Playgroud) 我试图弄清楚提升状态是如何工作的。目前,我正在尝试在不同的组件中使用 onPress 来更改状态。在我下面提供的小吃演示中,ListHome由于MapHome某种原因没有做出回应,但您仍然会看到我正在努力完成的任务。
我希望地图和列表“按钮”能够完成“单击此操作”的功能。
演示- 当前实现没有错误,只是除了可触摸不透明度的闪烁之外没有任何响应。(另请记住,由于某种原因,零食没有响应。我的本地设备工作正常)
编辑:所以要清楚,我希望能够whichComponentToShow从另一个组件访问和更改状态。即ListHome组件。
export default class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
visible: true,
whichComponentToShow: 'Screen1',
};
}
goToMap = () => {
this.setState({ whichComponentToShow: 'Screen2' });
};
render(){
if(this.state.whichComponentToShow === 'Screen1'){
return(
<View style={{backgroundColor: '#d1cfcf' ,flex: 1}}>
<ListHome
renderMap = {this.goToMap.bind(this)}
/>
}
}
Run Code Online (Sandbox Code Playgroud)
export default class ListHome extends React.Component {
goToMap = () => {
this.props.renderMap();
}
<TouchableOpacity onPress={() => this.goToMap.bind(this)}> …Run Code Online (Sandbox Code Playgroud) 我尝试导入聊天机器人上下文,以便在编辑中访问当前聊天机器人,但出了点问题。你知道这里可能是什么问题吗?
非常感谢!
这是我的 chatstate.js 的摘录:
// import packages
import React, { useReducer, useContext } from "react";
import axios from "axios";
// import local dependencies
import AuthContext from "../../Context/Auth/authContext";
import ChatbotContext from "../../Context/Chatbot/chatbotContext";
import chatReducer from "./chatReducer";
import ChatContext from "./chatContext";
import { ADD_INPUT_TO_CHAT, SESSION_ID_CREATED } from "./chatTypes";
const ChatState = props => {
// get access to auth token
const authContext = useContext(AuthContext);
const { token } = authContext;
// get access to current chatbot in edit
const chatbotContext …Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个名为hidden字典的状态变量(例如[{'cutomkey1':'somevalue', 'customkey2':'somevalue'}]:)。隐藏可以为空[{}]。
在我的一种方法中,我想将一个项目推{'asd':'asd'}送到隐藏状态变量并将它们相加。
我不断收到此错误:
输入“字符串[] | undefined' 不是数组类型。
我是打字稿新手,我不确定我是否正确设置了所有变量。这是我的代码(仅相关部分):
import React from 'react';
export type AppState = {
tickets?: Ticket[],
hidden?: Array<String>,
search: string;
}
export class App extends React.PureComponent<{}, AppState> {
state: AppState = {
search: '',
hidden: []
}
hideCard = (e: React.SyntheticEvent<EventTarget>) => {
let targ = e.target as HTMLElement
let parent = targ.parentElement as HTMLElement
let dict: Map<string, string> = new Map();
dict.set(parent.id, parent.id)
this.setState({
hidden: [...this.state.hidden, {dict}] …Run Code Online (Sandbox Code Playgroud) import { useState } from "react";
export default function App() {
const [buttonClicked, setButtonClicked] = useState(false);
console.log('Render');
return (
<div className="App">
<button onClick={() => setButtonClicked(true)}>Click me</button>
{buttonClicked && <div>Button was clicked</div>}
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
该组件未在StrictMode. 它首先渲染,因此我们在控制台中看到一个渲染。当我们单击按钮时,它会因状态更新而重新呈现。我们可以Render再次在控制台看到。但是,令我惊讶的是,当我们再次单击该按钮时,它也会重新渲染该组件,我们Render第三次在控制台中看到。
我认为状态更新正在检查值是否已更改,因此不会第三次渲染。
对我来说更奇怪的是,当我们第三次单击该按钮时,它不会重新渲染组件。
为什么会发生这种情况?
Codesandbox: https://codesandbox.io/s/proud-star-rg49x9? file=/src/App.js:0-336
react-state ×10
reactjs ×10
javascript ×6
react-hooks ×3
typescript ×3
jsx ×1
next.js ×1
node.js ×1
react-native ×1
rendering ×1
strict-mode ×1
use-context ×1