簡體   English   中英

為什么我的代碼不會同時加密字母並顯示出來?

[英]Why won't my code encrypt a letter and show it as well?

我正在嘗試進行加密,並希望首先測試一下如何更改單擊按鈕后提交的單個字母並顯示它。

例如,當用戶輸入a並單擊按鈕時,它應在瀏覽器中顯示x

我究竟做錯了什么?

import React, { Component } from 'react';

class Main extends Component {
    constructor(props) {
        super(props);

        this.state = {
            show: false
        };

        this.encrypt = this.encrypt.bind(this);
    }

    encrypt = () => {
        let input = document.getElementById("inputText").value;

        this.setState({show: true});

        switch(input) {
            case "a":
                return "x";

            default:
                return null;
        }
    };

    render() {
        return(
            <div>
                <input type="text" placeholder="type something" id="inputText"/>
                <button onClick={() => this.encrypt}>Click to encrypt</button>
                {
                    this.state.show ? this.encrypt() : null
                }
            </div>
        );
    }
}

export default Main;

我可能會用這種方式編寫您的代碼。 它對我有用。

class Main extends Component {
  constructor(props) {
    super(props);

    this.state = {
      encryptedValue: null
    };

  }

  encrypt = () => {
    let input = document.getElementById("inputText").value;

    let encryptedValue;
    switch (input) {
      case "a":
        encryptedValue = "x";
        break;
      default:
        encryptedValue = null;
    }

    this.setState({ show: true, encryptedValue: encryptedValue });
  };

  render() {
    return (
      <div>
        <input type="text" placeholder="type something" id="inputText" />
        <button onClick={() => this.encrypt()}>Click to encrypt</button>
        {this.state.encryptedValue}
      </div>
    );
  }
}
export default Main;

我不想更正您的代碼,因為它有很多缺點。

有很多事情不對,所以讓我仔細看看

  • 您正在使用一個箭頭函數並將其綁定到此,箭頭函數中的一個或另一個箭頭函數的作用類似於詞匯表,將其綁定到該上下文
  • 您在調用setState時會迫使重繪進入重繪循環並失敗
  • 您沒有在忘了()的onclick上調用encrpty

 class Main extends React.Component { state = { input: null, view: '' }; componentDidMount() { this.setState({input: document.getElementById("inputText")}) } encrypt = () => { const { value } = this.state.input; switch (value) { case "a": return this.setState({view: "x"}); case "b": return this.setState({view: "g"}); default: return null; } }; render() { return ( <div> <input type = "text" placeholder = "type something" id = "inputText"/> <button onClick={this.encrypt}> Click to encrypt </button> {this.state.view} </div> ); } } ReactDOM.render(< Main/> , document.getElementById('root')); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div> 

暫無
暫無

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

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