【问题标题】:How to get the value of react component - AceEditor如何获取 react 组件的值 - AceEditor
【发布时间】:2016-12-30 16:14:39
【问题描述】:

我在使用AceEditor反应组件https://github.com/securingsincity/react-ace时遇到以下问题

我使用AceEditor 作为用户输入,用户输入代码后,他(她)按下Run 按钮。 (见图)如何提取用户从AceEditor组件输入的文本?

【问题讨论】:

    标签: javascript reactjs ace-editor


    【解决方案1】:

    使用最新的 React v16.12+ this.refName.current.editor.getValue() 可以获取可以使用 JSON.parse 解析的字符串值。

    Ref 应该被实例化为:

     constructor(props) {
        super(props);
        this.refName = React.createRef();
      }
    

    并传递给 AceEditor 组件:

         <AceEditor
            ref={this.refName}
         />
    

    【讨论】:

      【解决方案2】:

      不必使用onChange。

      <AceEditor ref="aceEditor" />
      
      this.refs.aceEditor.editor.getValue()
      

      【讨论】:

        【解决方案3】:

        您需要将此状态绑定到类的构造函数中的 onchange 函数。它对我有用。

        constructor(props){
            super(props);
            this.state = {code:"code"};
            this.onChange = this.onChange.bind(this);
        }
        
        onChange(newValue) {
            this.state.code = newValue;
            alert(this.state.code);
        }
        

        Ace Editor 的 Onchange 是

        onChange = {
           this.onChange
        }
        

        【讨论】:

          【解决方案4】:

          AceEditor 提供了一个 onChange 事件,您可以在用户更改编辑器时使用该事件检索编辑器的当前内容,然后将值存储在您自己的数据存储或组件的状态中。

          这样,您可以在需要时检索该值。

          More about the editor's properties.

          自述文件还提供了an example,演示了它的用法。

          【讨论】:

            【解决方案5】:

            您需要订阅onChange 事件(在文档中进行了解释)并将传递给回调的值存储在某处,如果Run 按钮位于同一页面上,则可能在component's state 中。然后,当用户点击按钮时,只需通过this.state.xxx检索它

            【讨论】:

              猜你喜欢
              • 2016-06-18
              • 2021-01-15
              • 1970-01-01
              • 2020-04-30
              • 1970-01-01
              • 2020-03-25
              • 2019-10-27
              • 1970-01-01
              • 2019-09-29
              相关资源
              最近更新 更多