[英]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;
我不想更正您的代碼,因為它有很多缺點。
有很多事情不對,所以讓我仔細看看
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.