0

我在我的反应表单(formik 库)中使用以下内容来显示文本字段。

用户在文本字段中键入内容后,如何将文本字段的值存储在会话存储中?如果它是一个选择,我会添加Onclick将选择存储到会话存储中的功能。

import {Button, InputLabel,Menu,MenuItem, Select, TextField, TextareaAutosize} from '@material-ui/core'
import {styled} from "@material-ui/core/styles";

const StyledTextField = styled(TextField)( {
    width: '50%',
})

const CustomTextField = ({
                             placeholder,
                             ...props
                         }) => {
    const [field, meta] = useField(props);
    const errorText = meta.error && meta.touched ? meta.error : "";
    return (
        <div>
            <InputLabel>{placeholder}</InputLabel>
            <StyledTextField
                {...field}
                helperText={errorText}
                error={!!errorText}
            />
        </div>
    );
};



<CustomTextField name = "textDescription" type ="text" placeholder="Text Description"/>

我想将它存储在存储中的原因是因为我正在使用文件上传(高级)版本,并且一旦用户单击upload按钮,我想从存储中获取描述并在 api 调用中使用它。

输入内容后,我尝试使用以下内容:

  console.log("Printing Document By getElementbyID value");
            console.log(document.getElementById('textDescription').value);

但它继续打印Uncaught TypeError: document.getElementById(...) is null

基于 Bassam Rubaye 的回答的故障排除结果:

添加了这样的事件:

<StyledTextField
                    {...field}
                    helperText={errorText}
                    error={!!errorText}
                    onChange={handleChange}  
                />

并尝试了以下方法:

 const handleChange = e => {
        
        console.log("Value of Description");
        console.log(e.target.value);
        
    }

它在中打印如下console.log

Value of Description
t
Value of Description
te
Value of Description
tes
Value of Description
test

它会存储test在会话存储中吗?

4

1 回答 1

0

我不太确定您的用例,但是您可以在 StyledTextField 上为“onChange”事件添加一个处理程序,在该处理程序中,您可以将该组件的值添加到 sessionStorage

handleChange(e) {
 /** you will need to throttle the call here as well
     to avoid calling setItem with each change but only calling it after for example 300MS to make sure the user has completed typing
 */
 sessionStorage.setItem("yourKey", e.target.value);

}

于 2021-04-26T20:54:51.710 回答