javascript - 在 React 中使用 enter 提交输入字段?
问题描述
编辑:它正在输入提交,但不让我输入字符
我不知道为什么我收到一个错误,说无法读取未定义的属性“onKeyPressHandler”
React、Nextjs、Socket.io 和 Express 是我正在使用的一些东西。
我正在尝试这样做,每当您点击输入时,就会发送一条聊天消息,但我收到了该错误,我不太清楚为什么。
对不起,这可能是一个超级简单的问题,只是太晚了,所以我的大脑有点累了哈!
这是输入逻辑在 chat.js 中的文件:
import React from "react";
import styled from "styled-components";
import Sidebar from "../components/Sidebar";
import UserMessage from "../components/UserMessage";
import { Store, CTX } from '../components/Store'
const ChatBox = (props) => {
const [textValue, changeTextValue] = React.useState('');
const { allChats } = React.useContext(CTX);
console.log(allChats)
const onKeyPressHandler = (e) => {
if (e.key === 'Enter') {
sendChatAction(textValue)
changeTextValue('')
}
}
return (
<Layout>
<Sidebar />
<Wrapper>
<InnerBoxWrapper>
<InnerBox>
<UserMessage />
<input label="Send a chat" value={textValue} onKeyPress={onKeyPressHandler} />
</InnerBox>
</InnerBoxWrapper>
</Wrapper>
</Layout>
)
}
export default (props) => <Store><ChatBox {...props} /></Store>
在这里,我还将出于某种原因显示商店以防万一是上下文导致的?
Store.js -
import React from 'react'
import io from 'socket.io-client'
export const CTX = React.createContext();
const initState = {
general: [
{ from: 'user1', msg: 'hello' },
{ from: 'user2', msg: 'u stink' },
{ from: 'user3', msg: 'some other words' }
],
channel2: [
{ from: 'user1', msg: 'hello' }
]
}
const reducer = (state, action) => {
const { from, msg, channel } = action.payload;
switch (action.type) {
case 'RECEIVE_MESSAGE':
return {
...state,
[channel]: [
...state[channel],
{ from, msg }
]
}
default:
return state
}
}
const sendChatAction = (dispatch, socket) => {
socket.emit('chat message', value);
}
let socket;
export const Store = (props) => {
if (!socket) {
socket = io(':3001')
}
const [allChats, dispatch] = React.useReducer(reducer, initState)
return (
<CTX.Provider value={{ allChats, sendChatAction }}>
{props.children}
</CTX.Provider>
)
}
解决方案
推荐阅读
- ffmpeg - FFMPEG 帧提取 - 卡住
- javascript - 在可编辑 div 内的两个不可编辑跨度之间使用向右箭头移动光标
- python - 如何在 Python 中运行 PDFbookmarker
- java - 插件依赖的 Org.JSON
- api - 我的 oppproduct 中的 Swagger-YAML 错误映射条目
- java - Xpath 不适用于 HTMLUnit
- c# - Unity3D Speed Hack 检测
- css - Bootstrap 4 导航栏水平溢出
- nativescript - 绕过导航循环
- android - 如何为我的所有 android 项目设置 gradle 属性?