【问题标题】:Reactjs Typescript form input elements value not workingReactjs Typescript表单输入元素值不起作用
【发布时间】:2020-04-13 11:35:20
【问题描述】:

我是 React 新手,正在填写多步骤联系表。我制作了一个 handleChange 函数,我在其中获取输入的值,因此当我上一个或下一个时,会显示输入的内容,以便您对其进行编辑。第一个输入效果很好,但是当我将value={text} 放入第二个输入时出现问题,当我单击下一步时,它卡在第一个输入上。请帮忙。

import React, {useState} from "react";
import {useStep} from "react-hooks-helper";


const Contact: React.FC = () => {

    const [text, setText] = useState("")
    const {index, navigation: {previous, next},} = useStep({steps: 4});

    function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
        const {value} = e.target
        setText(value)
    }

    return (
        <div className="contact">
            <div className="contact-inner">
                <form>
                    {index === 0 && <label>
                        <input onChange={handleChange} value={text}  type="text" name="name"
                               placeholder={"Please enter your name"}/>
                    </label>}
                    {index === 1 && <label htmlFor="email">
                        <input  type="text" name="email" placeholder="Please enter your email"/>
                    </label>}
                    {index === 2 && <label>
                        <input  type="text" name="title"
                               placeholder="Please enter the title"/>
                    </label>}
                    {index === 3 && <label>
                        <textarea className="content" name="content" placeholder="Please enter your message"/>
                    </label>}


                </form>
                <div className="buttons">
                    <button className="previous" onClick={previous}>previous</button>
                    <button className="next" onClick={next}>{index === 3 ? 'Submit' : 'Next'}</button>
                </div>

            </div>
        </div>
    )
}

export default Contact

【问题讨论】:

    标签: reactjs typescript react-hooks


    【解决方案1】:

    现在您只有一个文本状态,您可能应该为每个输入创建一个状态:

    const [contact, setContact] = useState({
      name: "",
      email: "",
      title: ""
    });
    

    然后你可以为每个输入显示正确的值:

    <input name='email' value={contact.email} ...
    

    并更新您的 handleChange 函数:

    function handleChange(event) {
      const {name, value} = event.target;
      setContact({ ...contact, [name]: value });
    }
    

    【讨论】:

    • 感谢您的回答。在 setContact 的第一个状态上,我得到:“参数 'state' 隐含地具有 'any' 类型。”在花括号中我得到:“预期有 1 个参数,但有 4 个或更多。”
    • 试试这个:setContact({ ...contact, [name]: value });
    • 你能帮帮我吗.. 我需要文本区域中的 onChange 事件和值,与输入相同,但我收到错误...
    • textarea 的工作方式完全相同。将新内容添加到您的联系状态(内容:“”)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-10
    • 2015-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-30
    • 2018-08-21
    相关资源
    最近更新 更多