Trying to port web page project to React (web) 尝试将网页项目迁移到React(web)

huangapple go评论56阅读模式
英文:

Trying to port web page project to React (web)

问题

I'm here to help with the translation. Here's the translated code:

我对React非常新手但我无法在任何地方找到答案我看到了很多使用React Native的示例但这是用于PC上的Web查看)。我有一个非常简单的页面/应用目前使用HTMLCSSJS运行并允许用户按下键盘上的按键这些按键被映射为按钮来猜一个单词尝试将其重写为React似乎相当困难我想知道

A是否已经有人做过这个
B是否有人有关于如何将其转换为React组件的指针因为我找不到与导入React Native库无关的信息

我在简单的Web视图HTMLCSSJS中的JS如下所示

```javascript
function generateButtons() {
    /*
        字母字符串使用split()拆分为单个字母
        使用.map(letter => ...)将每个字母映射为一个函数
            buttonsHTML将所有字母作为<button>元素写入.html文件,并创建一个onClick事件监听器,
            该事件监听器调用handleGuess()函数
    */

    let buttonsHTML = 'abcdefghijklmnopqrstuvwxyz'.split('').map(letter =>
        `
            <button
            class="keys"
            id='${letter}'
            onClick="handleGuess('${letter}')"
            >
            ${letter}
            </button>
        `).join('');

    // 将buttonsHTML的值分配给HTML id键盘
    document.getElementById('keyboard').innerHTML = buttonsHTML;
}

而我的React应用程序目前非常简陋,如下(App.js):

import './App.css';
import React from 'react';

function GameTitle() {
  return (
    <h1>随机单词猜测游戏</h1>
  )
}

function GamePrompt() {
  return (
    <p>要猜的单词</p>
  )
}

function SetDifficulty() {
  return (
    <label>
      设置难度级别
      <select>
        <option value="setEasy">简单</option>
        <option value="setMedium">中等</option>
        <option value="setHard">困难</option>
      </select>
    </label>
  )
}

function GuessCounter() {
  return(
    <p>猜测次数 </p>
  )
}

const alphabet = [
  "A", "B", "C", "D", "E", "F", "G", "H", "I",
  "J", "K", "L", "M", "N", "O", "P", "Q", "R",
  "S", "T", "U", "V", "W", "X", "Y", "Z"
];

function GameKeyboard() {
  return(
    <>
    {alphabet.map(letter => (
        <button
          key={letter}
          className="keys"
          onClick={() => handleGuess(letter)}
        >
          {letter}
        </button>
    ))}
    </>
  )
}

function App() {
  return (
    <div>
      <>
        <GameTitle />
        <GamePrompt />
      </>
      <SetDifficulty />
      <GuessCounter />
      <GameKeyboard />
    </div>
  );
}

export default App;

我已经尝试重新创建了一个字母设置(使用const并显示它),但当我尝试实现映射到字母元素的按钮组件时,我无法找出正确的语法以将其用作<Button>组件。


<details>
<summary>英文:</summary>
I am incredibly new to React but I could not find this answer anywhere (I have seen a lot of examples using React-native but this is for web viewing on PC). I have a really simple page/app that runs using HTML, CSS, JS currently and allows the user to press keys on a keypad (which are mapped as buttons) to guess a word. Trying to rewrite this for React is proving pretty daunting and I was wondering if:
A) This is something that someone else has already done?
B) If someone has pointers on how to translate this over into a React component as I cannot find any information on this that is not directly related to importing react-native libraries?
My JS in the simple web view (HTML, CSS, JS) looks like this:

function generateButtons() {
/*
alphabet str is split into individual letters with split()
each letter is mapped with a function .map(letter => ...)
buttonsHTML write all letters as <button> elements within
the .html file and creates an onClick event listener that
calls handleGuess() function
*/

    let buttonsHTML = &#39;abcdefghijklmnopqrstuvwxyz&#39;.split(&#39;&#39;).map(letter =&gt;
`
&lt;button
class=&quot;keys&quot;
id=&#39;` + letter + `&#39;
onClick=&quot;handleGuess(&#39;` + letter + `&#39;)&quot;
&gt;
` + letter + `
&lt;/button&gt;
`).join(&#39;&#39;);
// assigns the value of html id keyboard to buttonsHTML 
document.getElementById(&#39;keyboard&#39;).innerHTML = buttonsHTML;
}

And my incredibly barebones React app currently looks like this (App.js):

import './App.css';
import React from 'react';

function GameTitle() {
return (
<h1>Random Word Guessing Game</h1>
)
}

function GamePrompt() {
return (
<p>Word to be guessed:</p>
)
}

function SetDifficulty() {
return (
<label>
Set difficulty level:
<select>
<option value="setEasy">Easy</option>
<option value="setMedium">Medium</option>
<option value="setHard">Hard</option>
</select>
</label>
)
}

function GuessCounter() {
return(
<p>Number of guesses: </p>
)
}

const alphabet = [
"A", "B", "C", "D", "E", "F", "G", "H", "I",
"J", "K", "L", "M", "N", "O", "P", "Q", "R",
"S", "T", "U", "V", "W", "X", "Y", "Z"
];

function GameKeyboard() {
return(
<>
{alphabet}
</>
)
}

function App () {
return (
<div>
<>
<GameTitle />
<GamePrompt />
</>
<SetDifficulty />
<GuessCounter />
<GameKeyboard />
</div>

);
}

export default App;


I have tried re-creating an alphabet set-up (using `const` and displaying it) but when I try to implement a button component mapped to the alphabet elements I have not been able to figure out the correct syntax to allow it to be used as a &lt;Button&gt; component.
</details>
# 答案1
**得分**: 1
I think what you need is to use `map()` in the JSX. In this example, the `handleGuess()` function is passed into the `<AlphabetButtons>` component by its parent, but you could put it directly inside `<AlphabetButtons>` if you wanted to.
```javascript
function AlphabetButtons({ handeGuess }) {
return (
<div>
{alphabet.map((letter) => (
<button
onClick={() => {
handeGuess(letter);
}}
>
{letter}
</button>
))}
</div>
);
}

See here for a working example codesandbox.io

英文:

I think what you need is to use map() in the JSX. In this example the handleGuess() function is passed into the &lt;AlphabetButtons&gt; component by it's parent, but you could put it directly inside &lt;AlphabetButtons&gt; if you wanted to.

function AlphabetButtons({ handeGuess }) {
  return (
    &lt;div&gt;
      {alphabet.map((letter) =&gt; (
        &lt;button
          onClick={() =&gt; {
            handeGuess(letter);
          }}
        &gt;
          {letter}
        &lt;/button&gt;
      ))}
    &lt;/div&gt;
  );
}

See here for a working example codesandbox.io

huangapple
  • 本文由 发表于 2023年5月11日 04:52:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76222473.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定