【问题标题】:React not displaying text upon form submission提交表单时反应不显示文本
【发布时间】:2021-09-07 00:09:38
【问题描述】:

我正在尝试接受输入,然后在提交表单后显示它,但它没有被显示。

我首先使用一个钩子来获取输入字段中的文本。按下按钮后,我运行一个函数,该函数使用另一个钩子并将其值设置为输入字段中的文本。然后将其放入渲染中。

我遇到的问题是,我一提交表单,屏幕就一片空白。 我在下面附上了我的代码。

import React from "react";
    import { useState } from "react";

    const App = () => {
        const [Text, setText] = useState('');
        const [Input, setInput] = useState('');
        const showInp = (e) => {
            e.preventDefault();
            setInput(Text);
        };
        return(
            <div className="Main">
                <p>
                    The following cryptocurrencies are available: Bitcoin(BTC).
                </p>
                <form onSubmit={showInp}>
                    <label htmlFor="CurrencyName">Currency Name: </label>
                    <input type="text" className="CurrencyName" value={Text} onChange={(e) => setText(e.target.value)} />
                    <button style={{marginLeft:"5px"}} type="submit">Submit</button>
                </form>
                {Input !== '' &&(
                    {Input}
                )}
            </div>
        )
    }
    export default App;

任何帮助将不胜感激。

【问题讨论】:

    标签: javascript html reactjs forms


    【解决方案1】:

    渲染Input 值时出现语法错误。而不是Input 值,您正在渲染一个具有Input 键且其值为Input 的对象,并且react 无法渲染对象,它将引发错误。

    import React from 'react';
    import { useState } from 'react';
    
    const App = () => {
      const [Text, setText] = useState('');
      const [Input, setInput] = useState('');
      const showInp = e => {
        e.preventDefault();
        setInput(Text);
      };
      return (
        <div className="Main">
          <p>The following cryptocurrencies are available: Bitcoin(BTC).</p>
          <form onSubmit={showInp}>
            <label htmlFor="CurrencyName">Currency Name: </label>
            <input
              type="text"
              className="CurrencyName"
              value={Text}
              onChange={e => setText(e.target.value)}
            />
            <button style={{ marginLeft: '5px' }} type="submit">
              Submit
            </button>
          </form>
          {/* Below line had error */}
          {Input !== '' && Input}
        </div>
      );
    };
    export default App;
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-08
      • 1970-01-01
      • 2018-11-28
      • 1970-01-01
      • 2021-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多