我设法在网页上添加了一个输入字段,但不知道如何获取该输入,将其作为字符串传递给函数并将结果呈现到我的网页上。
下面是我的代码,后面是我要传递用户输入的功能。
import React, { Component } from 'react';
import logo from './caesar.png';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Caesar's Cipher (Rot-13), built with React. See the code</h2>
</div>
<p className="App-intro">
The Caesar Shift is a famous encryption technique used by Julius Caesar around 100 years BC.
</p>
<p className="App-intro">
It consists of taking in a message and shifting all of its letters by 13 numbers in the alphabet.
</p>
<p className="App-intro">
In the example below, A will become N, the 13th letter in the alphabet:
</p>
<h1 className="App-background">
"A" --> "N"
</h1>
<p className="App-intro">
The same can be done with whole words and sentences:
</p>
<h1 className="App-background">
"Attack Friday midnight" --> "Nggnpx Sevqnl zvqavtug"
</h1>
<div class="ui input"><input type="text" placeholder="Encrypt something!" /></div>
</div>
);
}
}
export default App;
// function I want to have the input passed to.
let alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
const caesar = input => {
let splitName = input.toLowerCase().split(''), convertedString = [], newLetter;
for (i = 0; i < splitName.length; i++) {
if (splitName[i] === ' ') {
convertedString.push(splitName[i])
}
for (j = 0; j < alphabet.length; j++) {
if (splitName[i] === alphabet[j]) {
newLetter = alphabet[j + 13];
if (newLetter === undefined) {
newLetter = alphabet[j - 13];
}
convertedString.push(newLetter);
}
}
} console.log(convertedString.join(''))
}
caesar(input)
我找不到与此问题相关的任何帖子
答案 0 :(得分:1)
import React, { Component } from 'react';
import logo from './caesar.png';
import './App.css';
class App extends Component {
state = {
result: ''
}
caesar = e => {
// get input with e.target.value
const result = // apply your function to input
this.setState({ result })
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Caesar's Cipher (Rot-13), built with React. See the code</h2>
</div>
<p className="App-intro">
The Caesar Shift is a famous encryption technique used by Julius Caesar around 100 years BC.
</p>
<p className="App-intro">
It consists of taking in a message and shifting all of its letters by 13 numbers in the alphabet.
</p>
<p className="App-intro">
In the example below, A will become N, the 13th letter in the alphabet:
</p>
<h1 className="App-background">
"A" --> "N"
</h1>
<p className="App-intro">
The same can be done with whole words and sentences:
</p>
<h1 className="App-background">
"Attack Friday midnight" --> "Nggnpx Sevqnl zvqavtug"
</h1>
<div class="ui input"><input onChange={this.caesar} type="text" placeholder="Encrypt something!" /></div>
<div>{this.state.result}</div> // <-- Render result here
</div>
);
}
}