首页 > 解决方案 > 在 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>
    )
}

标签: javascriptreactjsnext.js

解决方案


添加onChange处理程序

const onChangeHandler = e => {
  changeTextValue(e.target.value);
}
...

return (
  ...
  <input
    label="Send a chat"
    onChange={onChangeHandler}
    value={textValue}
    onKeyPress={onKeyPressHandler}
  />
  ...
);

编辑史诗里奇-ch8j3

注意:从语义上讲,使用表单并提交机制更正确,但这超出了您的问题范围。


推荐阅读