我在react组件中有一个输入来存储名称:
<input key="marker-name" id="marker-name" name="marker-name" onChange={handleRename} type="text" value={name} />我已经为它编写了以下处理程序:
const handleRename = ({ target }) => {
setPerception({
...perception,
name: target.value
})
}然而,它并不像预期的那样工作,如果用户试图删除现有的名称,那么一旦输入中的最后一个字符被删除(即输入为空),先前的值就会弹回。

以下是该组件的完整代码:
import React, { useState, useEffect } from 'react'
// import custom styles for child component
import './styles.scss'
const MarkerName = ({ store, onStoreUpdate, callbackFunction }) => {
const [clicked, setClicked] = useState(false)
const [perception, setPerception] = useState(null)
const [currentMarkerName] = useState(store.currentMarkerName)
const [currentMarkerForce] = useState(store.currentMarkerForce)
const [currentForce] = useState(store.currentForce)
// A copy of the store to capture the updates
const newStore = store
// Only populate the perception state if it's store value exists
useEffect(() => {
store.perception && setPerception(store.perception)
}, [])
// Only show the form to non-umpire players who cannot see the correct name
const clickHander = () =>
currentForce !== 'umpire' &&
currentForce !== currentMarkerForce &&
setClicked(true)
const handleRename = ({ target }) => {
setPerception({
...perception,
name: target.value
})
newStore.perception.name = target.value
onStoreUpdate(newStore)
}
const handleSubmit = e => {
e && e.preventDefault()
callbackFunction(newStore)
}
const handleRevert = e => {
e.preventDefault()
setPerception({
...perception,
name: null
})
newStore.perception.name = null
onStoreUpdate(newStore)
handleSubmit()
}
const name = perception && perception.name ? perception.name : currentMarkerName
return (
<>
<h2 key="header" onClick={clickHander}>{name}</h2>
{
clicked &&
<div className="input-container marker-name">
<label>
Update asset name
<input key="marker-name" id="marker-name" name="marker-name" onChange={handleRename} type="text" value={name} />
</label>
<button type="submit" onClick={handleSubmit}>Rename</button>
<button onClick={handleRevert}>Revert</button>
</div>
}
</>
)
}
export default MarkerName发布于 2020-02-06 22:51:51
据我所知,这一行是问题所在:
const name = perception && perception.name ? perception.name : currentMarkerName;每次字符更改时都要重新渲染(onChange={handleRename})。一旦删除了所有字符,perception && perception.name的计算结果就是true && false (空字符串是假的),即false。因此该组件是使用const name = currentMarkerName呈现的。由于currentMarkerName尚未更改,因此使用旧名称重新呈现。
改用下面的代码:
const name = perception && typeof perception.name !== 'undefined' ? perception.name : currentMarkerName;发布于 2020-02-06 23:07:36
在React表单是受控组件中,您几乎可以获得它,但是在将感知值分配给inputValue...that之前,您检查它的值似乎是不正确的。
您是否可以尝试进行这些更改,并让我们看看效果: 1.对于感知的状态值,将初始值设为任何空字符串:const [perception, setPerception] = useState(null)
forminput上的
https://stackoverflow.com/questions/60096667
复制相似问题