在react js中为字母分配数字


  • 首先,我想给所有字母分配数字,像这样:a=1,b=2,c=3,d=4等。

  • 其次,我想创建一个输入字段和提交按钮。

  • 第三,当我在输入字段中输入字母时,(例如:abcd显示1234,因为我已经在上面提到过,a=1, b=2, c=3, d=4)。

  • 最后,我想添加它们(例如:我输入"abcd"输出是1234,将它们相加)abcd的最终输出为1+2+3+4 =10。

    import React,{useState} from ' React '导入". ./node_modules/引导/dist/css/bootstrap.min.css"

const Data = () =>{const[数据,setData] = useState ({1, b: 2, c: 3 d: 4 e: 5 f: 6 g: 7, h: 8,我:9日珍:10 k: 11日,李:12 m: 13 n: 14 o: 15日p: 16,问:17日r: 18岁的年代:19日,师:20,u: 21日v: 22日w: 23日,x: 24日,y: 25日,z: 26})

const changeHandler = e => {
setData({...data,[e.target.name]:[e.target.value]})


}
const submitHandler=e=> {
e.preventDefault();

}
return (
<div>
<form onSubmit={submitHandler}>
<input type="text"onChange={changeHandler}/><br/>
<button className="btn btn-primary"onClick={()=>setData(console.log(data))}>Click</button><br/>
</form>

</div>

)}

导出默认数据

下面是实现预期目标的一种可能方法。

<<p>

代码片段/strong>

const {useState} = React;
const Thingy = ({...props}) => {
// state variable to hold user input
const [userInput, setUserInput] = useState('');

// state variable to track user submit button click
const [showResult, setShowResult] = useState(false);

// method to update "userInput" state variable
const handleChange = ev => (setUserInput(ev.target.value), setShowResult(false));

// method to conver a single character (a to z) into number (1 to 26)
const convertChar = ch => {
const c = ch.toLowerCase();
// if user input is a digit, ensure return value is a "string"
if ('0' <= c && c <= '9') return ch.toString();
if (!('a' <= c && c <= 'z')) return ch;         // do not convert non-alpha
return c.charCodeAt(0) - 'a'.charCodeAt(0) + 1;
};

// method to transform user-input into numbers
const transformInput = () => userInput
.split('')                    // split the string into array of individual letters
.map(c => convertChar(c))     // use the "convertChar" method
.join(' ');                   // join back to string with "space" seperator
// added a "space" only for rendering to UI
// method to find the sum/total of numbers
const getResult = () => userInput
.split('')                  // convert string to array of individual letters
.map(c => convertChar(c))   // transform a-z to numbers 1-26
.filter(                    // discard any characters except a-z, A-Z
c => (
typeof c !== 'string' &&    // check letter is no longer "string"
!isNaN(c)                   // and it is not "NaN"
)
)
.reduce(                    // add the numbers using ".reduce()"
(total, itm) => total + itm, 0
);

// return the JSX that will be rendered on the UI
// ----
// description of elements
// ^^^^^^^^^^^ ^^ ^^^^^^^^
// 1. label - "enter text" to prefix the input-box
// 2. input - to obtain the user input
// 3. "<p>" - paragraph elt to show a-z transformed to 1-26
// 4. button - submit button to calculate the sum
// 5. "<p>" - paragraphe elt to show the result of the summation
// -----
// NOTE: Items 4, 6 and conditionally rendered
return (
<div>
<div>
<label htmlFor={'usrinp'}>Enter text: </label>
<input
id="usrinp"
value={userInput}
onChange={handleChange}
/>
</div>
{
userInput.length > 0 &&
<p>Converted text to: {transformInput()}</p>
}
<button onClick={() => setShowResult(true)}>
Submit
</button>
{
showResult && <p>Result is: {getResult()}</p>
}
</div>
);
};
ReactDOM.render(
<div>
<h4>Transform User input text to numbers</h4>
<Thingy />
</div>,
document.getElementById("rd")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="rd" />

在上面的代码片段中添加内联注释。

你可以这样做

const dictionary = Object.fromEntries(Array(26).fill('a').map((s, i) => [String.fromCharCode(s.charCodeAt() + i), i + 1]))

export default function App() {

const [string, setString] = useState('')
const [numbers, setNumbers] = useState([])
const [total, setTotal] = useState(0)
const changeHandler = (e) => {
setString(e.target.value)
}
useEffect(() => {
setNumbers(
string.toLowerCase().split('').map(c => dictionary[c])
)
}, [string])
const calculateTotal = () => {
setTotal(numbers.reduce((a, b) => a + b, 0))
}


return (
<div className="App">
<div>{numbers.join(' ')}</div>
<input type="text" onChange={changeHandler} value={string}/><br/>
<button className="btn btn-primary"onClick={calculateTotal}>Click</button><br/>
{total > 0 && <div>the total is {total} }
</div>
);
}

最新更新