我有以下内容:
import numpy as np
import matplotlib.pyplot as plt
import cv2
import pywt
import pywt.data
# Load image
original = cv2.imread('/content/drive/My Drive/Colab Notebooks/Asplab/fgsm/watermark1.JPEG')
original = cv2.cvtColor(original, cv2.COLOR_BGR2GRAY)
# Wavelet transform of image, and plot approximation and details
titles = ['Approximation', ' Horizontal detail',
'Vertical detail', 'Diagonal detail']
coeffs2 = pywt.dwt2(original, 'bior1.3')
LL, (LH, HL, HH) = coeffs2
fig = plt.figure(figsize=(12, 3))
for i, a in enumerate([LL, LH, HL, HH]):
ax = fig.add_subplot(1, 4, i + 1)
ax.imshow(a, interpolation="nearest", cmap=plt.cm.gray)
ax.set_title(titles[i], fontsize=10)
ax.set_xticks([])
ax.set_yticks([])
fig.tight_layout()
plt.show()
并且我正在尝试使用此方法处理表单,在表单中用新创建的值填充表单:
interface Message {
message?: {
title?: string;
description?: string;
body?: string;
};
}
const [message, setMessage] = useState<Message>({
message: {
title: "",
description: "",
body: "",
},
});
但是问题是当我提交表格时我没有得到我的值意味着我的状态没有被创建的值更新,我认为我在提取字段时错过了一些东西,还有一种方法可以避免为每个字段使用ref我有田吗?有什么帮助吗?
更新:
答案 0 :(得分:1)
嘿,创建状态时,您需要这样定义它:
useState<Message>({
message: {
title: "",
description: "",
body: "",
},
})
但是在更新时,您会像这样:
setMessage(
{
...message,
[field]: event.target.value
}
)
看到区别了吗?应该是这样的:
setMessage(
{
message: {
...message.message,
[field]: event.target.value
}
}
)
这样,您将更新正确的内容,否则,将在对象的message
级别附近创建新字段,但是您想更新对象的message
字段内的字段
编辑:
要解决该错误,您需要引入一个深层次的类型,因此当您说keyof
时,它将指向正确的键。
interface MessageFormValues {
title?: string
description?: string
body?: string
}
interface Message {
message: MessageFormValues
}
const handleMessageInput = (
event: React.ChangeEvent<HTMLInputElement>,
field: keyof MessageFormValues,
) => {
setMessage({
message: {
...message.message,
[field]: event.target.value,
}
})
}