输入值清除-React Hooks

 收藏

我正在尝试使用useRef单击按钮后清除输入内容,这是我的代码

单击按钮后,我清除了状态和输入值
    const [giftCode, setGiftCode] = useState('');
    const inputGift = useRef(null);
    const clickHandler = () =>{
       setGiftCode('');  
       inputGift.current.value = '';
     }

                        <TextInput
                            type="text"
                            field="gift-card-code"
                            ref={inputGift}
                            autoComplete="off"
                            onChange={event => {
                                setGiftCodeError(false);
                                setGiftBalanceCheck(null);
                                setGiftCode.bind(event.target.value);
                            }}
                        />

The input value is clearing, but the state showing the browser debugger is not changing, if we changed the input filed then the state is changing, useState setGiftcode is not changing the component actual state is there any alternate way to do this. see the below image for the understanding. enter image description here

回复
  • 说不出口的爱 回复

    为什么不使用ref。在输入中将状态指定为值?

    
    
    const [giftCode, setGiftCode] = useState('');
        const clickHandler = () =>{
           setGiftCode('');  
         }
    
        ...
            <TextInput
                 type="text"
                 field="gift-card-code"
                 value={giftCode} // this
                 autoComplete="off"
                 onChange={event => {
                        setGiftCodeError(false);
                        setGiftBalanceCheck(null);
                        setGiftCode.bind(event.target.value);
                  }}
             />