javascript - React: controlled inputs in functional components using useState - Stack Overflow

I'm trying to write a functional ponent that includes an <input>, but I'm getting the &

I'm trying to write a functional ponent that includes an <input>, but I'm getting the "A ponent is changing an uncontrolled input of type text to be controlled." error and can't figure out what I'm doing wrong.

I've reduced my code to this, which reproduces the problem:

function Input({ value, onChange }) {
    const [text, setText] = useState(value);

    function update(event) {
        setText(event.target.value);
        if (typeof onChange === "function") {
            onChange(event.target.value);
        }
    }

    return (
        <input type="text" value={text} onChange={update} />
    );
}

I'm not quite sure how to use useState here to make this a controlled element—because this is clearly not working :(

What am I doing wrong?

I'm trying to write a functional ponent that includes an <input>, but I'm getting the "A ponent is changing an uncontrolled input of type text to be controlled." error and can't figure out what I'm doing wrong.

I've reduced my code to this, which reproduces the problem:

function Input({ value, onChange }) {
    const [text, setText] = useState(value);

    function update(event) {
        setText(event.target.value);
        if (typeof onChange === "function") {
            onChange(event.target.value);
        }
    }

    return (
        <input type="text" value={text} onChange={update} />
    );
}

I'm not quite sure how to use useState here to make this a controlled element—because this is clearly not working :(

What am I doing wrong?

Share asked Mar 11, 2019 at 17:59 Nicolás SanguinettiNicolás Sanguinetti 2884 silver badges9 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 11

You are most likely not passing in a value prop to your Input ponent, which will cause text to be undefined initially, and when you set the text in update, it bees controlled.

You can change your code to pass in a value prop to Input every time you use it, or give value a default value of an empty string.

function Input({ value = "", onChange }) {
    const [text, setText] = useState(value);

    function update(event) {
        setText(event.target.value);
        if (typeof onChange === "function") {
            onChange(event.target.value);
        }
    }

    return (
        <input type="text" value={text} onChange={update} />
    );
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743690068a4490813.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信