簡體   English   中英

使用帶有功能組件的 react-codemirror2

[英]use react-codemirror2 with functional component

我正在使用帶有功能組件的 react-codemirror2,我需要從 onKeyDown 事件處理程序中的本地 state 訪問一個值,但它似乎是this變化的上下文。 我不知道有什么方法可以在功能組件中綁定 this 的值,那么如何訪問handleKeyPress中的input值? 我只需要使用基於 class 的組件嗎? (我的應用程序也使用樣式化組件,但在這個問題的上下文中可以忽略它。)

const Console = () => {
  const [input, setInput] = useState('');
  
  // has a value here
  console.log('input: ', input);

  const handleKeyPress = (editor, event) => {
    if (event.keyCode === KEY_CODES.ENTER) {
      // empty here
      console.log('input: ', input);
    }
  };

  return (
    <StyledContainer>
      <IconButton disabled={true} icon={<RightOutlined />} />
      <Container>
        <CodeMirror
          value={input}
          options={{
            lineNumbers: false,
            foldGutter: false,
            styleActiveLine: false,
            autofocus: true,
            theme: 'material',
            mode: 'javascript',
          }}
          onBeforeChange={(editor, data, code) => setInput(code)}
          onKeyDown={(editor, event) => handleKeyPress(editor, event)}
        />
      </Container>
    </StyledContainer>
  );
};

我認為有兩種選擇:

  1. 您可以使用 react-codemirror2 作為基於類的組件或

  2. 您可以使用onKeyUp事件而不是onKeyDown並獲取編輯器的值,如下所示:

     const handleKeyPress = (editor, event) => { if (event.keyCode === KEY_CODES.ENTER) { // will return editor value console.log('input: ', editor.getValue()); } };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM