kir*_*imi 8 reactjs react-native
我有一个数组列表,当我开始在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>
)
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)
它会起作用。知道如何解决这个问题吗?
任何建议或评论将不胜感激!
提前致谢!
将Desktop组件移出MyApp组件可解决此问题。这样做的主要原因是Desktop组件在每次渲染时(每次键入时)都会重新创建,这会导致输入元素失去焦点。您也可以通过使用useCallback和useMemo钩子来稍微缓解这种情况,官方 React 文档中对两者都有详细描述,但在本示例中不需要它们。
另请参阅有关在组件中声明其他组件的答案。
| 归档时间: |
|
| 查看次数: |
356 次 |
| 最近记录: |