我正在尝试加密,并且想测试一下如何更改单击按钮后提交的单个字母并显示它。
例如,当用户输入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;
答案 0 :(得分:2)
我可能会以此方式编写您的代码。它对我有用。
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;
我不想更正您的代码,因为它有很多缺点。
答案 1 :(得分:0)
有很多错误,所以让我仔细看看
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>