gpt4 book ai didi

reactjs - 过滤数据时 react 输入字段将失去焦点

转载 作者:行者123 更新时间:2023-12-03 13:24:15 27 4
gpt4 key购买 nike

我有一个数组列表,当我开始输入 input 时数组列表将过滤对应于 value 。它有效,但我在 input 中失去了焦点输入一个字符后。

我的代码:

const MyPage = (props) => {

const [searchTerm, setSearchTerm] = useState("");

const results = !searchTerm
? people
: people.filter(person =>
person.toLowerCase().includes(searchTerm.toLocaleLowerCase())
);

const handleChange = event => {
setSearchTerm(event.target.value);
};

const Desktop = ({ children }) => {
const isDesktop = useMediaQuery({ minWidth: 992 })

return (
isDesktop?
<View>
<input
type="text"
placeholder="Search"
value={searchTerm}
onChange={handleChange}
/>
<View style={{width:100, height:100, backgroundColor:'red'}}>
{results.map(item => (
<Text>{item}</Text>
))}
</View>
</View>
:null
)
}

return(
<View style={{width:'100%',justifyContent:'center'}}>
<Desktop/>
</View>
)
}

而不是返回 <Desktop/>如果我直接输入

<input
type="text"
placeholder="Search"
value={searchTerm}
onChange={handleChange}
/>
<View style={{width:100, height:100, backgroundColor:'red'}}>
{results.map(item => (
<Text>{item}</Text>
))}
</View>

它会起作用的。知道如何解决这个问题吗?

任何建议或评论将不胜感激!

提前致谢!

最佳答案

Moving the Desktop component outside of the MyApp组件修复了这个问题。造成这种情况的主要原因是 Desktop 组件会在每次渲染时重新创建(每次键入时),这会导致输入元素失去焦点。您还可以通过使用 useCallbackuseMemo 钩子(Hook)(两者 described in detail in the official React documentation)来稍微缓解这种情况。 ,但在本例中不需要它们。

另请参阅this answer on declaring other components within a component .

关于reactjs - 过滤数据时 react 输入字段将失去焦点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60088621/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com