React获取onClick的Codemirror值

时间:2019-07-14 04:01:06

标签: reactjs codemirror react-codemirror

我正在尝试获取以下代码,以在单击按钮时显示CodeMirror onChange值,然后在“输出” div中显示该值。

我的反应还很陌生,所以不确定是通过状态传递值还是最好的方法。

到目前为止,这是我的代码:

import React, { Component } from "react";
import { UnControlled as CodeMirror } from "react-codemirror2";
import "codemirror/mode/javascript/javascript";
import "codemirror/lib/codemirror.css";

export default class Code extends Component {
  render() {
    return (
      <div>
        <CodeMirror
          value='console.log("Hello World")'
          options={{
            mode: "javascript",
            lineNumbers: true
          }}
          onChange={(editor, data, value) => {
            console.log(value);
          }}
        />
        <button onClick={}>run code</button>

        <div className="Output">
          <p>// Value should go here</p>
        </div>
      </div>
    );
  }
}

2 个答案:

答案 0 :(得分:0)

在这种情况下,您需要添加状态:

export default class Code extends Component {
    state={
       value: ''
     }
  render() {
    return (
      <div>
        <CodeMirror
          value='console.log("Hello World")'
          options={{
            mode: "javascript",
            lineNumbers: true
          }}
          onChange={(editor, data, value) => {
            this.setState({value});
          }}
        />
        <button onClick={}>run code</button>

        <div className="Output">
          <p>{this.state.value}</p>
        </div>
      </div>
    );
  }
}

答案 1 :(得分:0)

您可以使用state来维护您的值,并显示您的状态输出,

class Code extends Component {
  constructor(props) {
    super(props)
    this.state = {
      runCode: false,
      outputText: 'console.log("Hello World")',
    }
  }
  runCode = () => {
    this.setState({runCode: true})
  }
  render() {
    return (
      <div>
        <CodeMirror
          value={this.state.outputText}
          options={{
            mode: 'javascript',
            lineNumbers: true,
          }}
          onChange={(editor, data, value) => {
            this.setState({
              runCode: false,
              outputText: value,
            })
          }}
        />
        <button onClick={this.runCode}>run code</button>

        <div className="Output">
          <pre>{this.state.runCode && this.state.outputText}</pre>
        </div>
      </div>
    )
  }
}

Demo-单击按钮后附加输出。

Demo1-输入时附加了outout。