【问题标题】:use react-codemirror2 with functional component使用带有功能组件的 react-codemirror2
【发布时间】:2021-03-08 20:15:52
【问题描述】:

我正在使用带有功能组件的 react-codemirror2,我需要从 onKeyDown 事件处理程序中的本地状态访问一个值,但似乎this 的上下文发生了变化。我不知道有什么方法可以在函数组件中绑定 this 的值,那么如何访问 input 内部的值 handleKeyPress ?我只需要使用基于类的组件吗? (我的应用程序也使用了样式化组件,但在这个问题的上下文中可以忽略它。)

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>
  );
};

【问题讨论】:

    标签: javascript reactjs codemirror


    【解决方案1】:

    我认为有两种选择:

    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());
          }
       };
      

    【讨论】:

      猜你喜欢
      • 2020-12-30
      • 2020-08-14
      • 2020-06-25
      • 2022-07-02
      • 2020-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-06
      相关资源
      最近更新 更多