编辑:它正在处理提交的输入,但不允许我输入字符
我不确定为什么会收到错误消息“无法读取未定义的属性“onKeyPressHandler””
React、Nextjs、Socket.io 和 Express 是我正在使用的一些东西。
我试图让每当你按下回车键时都会发送一条聊天消息,但我收到了该错误,我不太确定为什么。
抱歉,这可能是一个非常简单的问题,只是太晚了,所以我的大脑有点累了哈!
这是输入逻辑所在的文件 聊天.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>
)
}
最佳答案
添加 onChange
处理程序
const onChangeHandler = e => {
changeTextValue(e.target.value);
}
...
return (
...
<input
label="Send a chat"
onChange={onChangeHandler}
value={textValue}
onKeyPress={onKeyPressHandler}
/>
...
);
注意:从语义上讲,使用表单和提交机制更正确,但这超出了您的问题范围。
关于javascript - 在 React 中使用 Enter 提交输入字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61437501/