简体   繁体   English

使用 Hooks 响应 InputForm 值

[英]React InputForm Value With Hooks

I am a bit new to hooks, and I can't seem to get my FormControl value to display its value correctly after being changed, the value stays the same on the page.我对钩子有点陌生,我似乎无法让我的 FormControl 值在更改后正确显示其值,该值在页面上保持不变。

However I can see that customerNameChanged is being called and customer object is being updated correctly in state, but the value used on the FormControl does not update.但是,我可以看到正在调用 customerNameChanged,并且正在 state 中正确更新客户 object,但 FormControl 上使用的值没有更新。

I don't understand why, but I assume it is because the value is a property of an object.我不明白为什么,但我认为这是因为该值是 object 的属性。 Can anyone explain further?谁能进一步解释?

export default function Customer(props) {

    const { match } = props;
    const [loading, setLoading] = useState(true);
    const [customer, setCustomer] = useState({});
    const [params] = useState(match.params);

    useEffect(() => {
        async function load() {
            const customer = await loadCustomer(params.id);
            setCustomer(customer.data);

            setLoading(false);
        }
        load();
    }, [])

    function customerNameChanged(event) {
        customer.name = event.target.value;
        setCustomer(customer);
    }

    function renderCustomer() {
        return (<div>
            <InputGroup className="mb-3">
                <InputGroup.Prepend>
                    <InputGroup.Text id="basic-addon1">Name</InputGroup.Text>
                </InputGroup.Prepend>
                <FormControl
                    placeholder="Name"
                    aria-label="CustomerName"
                    aria-describedby="basic-addon1"
                    value={customer.name}
                    onChange={customerNameChanged}
                />
            </InputGroup>
        </div>)
    }

    return (<Card><LoadedContent isLoading={loading} content={renderCustomer()} /></Card>)
}

This was the solution, thanks to @Ibz for the answer!这是解决方案,感谢@Ibz 的回答!

function customerNameChanged(event) {
    setCustomer({ ...customer, name: event.target.value });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM