javascript - 如何让自定义搜索输入可重用?
在我的应用程序中,最常用的元素之一是搜索输入框,它可以用来搜索产品、主题、类别等。
我已经创建了搜索输入元素,请看下面。
如何使导航栏搜索输入可重用,以便我可以在其他地方使用它?
import React from 'react'
import { Box, FormControl, InputBase } from '@mui/material'
import { styled } from '@mui/material/styles';
import { ContainedButton } from '../../ui-kit';
const StyledInput = styled(InputBase)(({ theme }) => ({
color: 'inherit',
border: 'none',
outline: 'none',
'& .MuiInputBase-input': {
maxHeight: '30px',
padding: '4px 16px',
maxWidth: '100%',
borderLeft: `1px solid ${theme.palette.grey[100]}`,
fontSize: 16,
lineHeight: 1.125,
color: theme.palette.text.primary,
},
width: '100%',
}));
const CONTAINED_BUTTON_STYLED = {
minWidth: '111px',
borderRadius: '0 2px 2px 0',
};
export const SearchInput = () => {
return (
<Box>
<FormControl sx={{ flexDirection: 'row', ml: '16px', width: '100%' }}>
<StyledInput placeholder="Search on Website" />
<ContainedButton sx={CONTAINED_BUTTON_STYLED} title="Search" />
</FormControl>
</Box>
)
}
答案#1
你可以简单地将所有 InputBase 的属性公开为你自定义 SearchInput 组件的属性,这样你就可以保持相同的完整 API,并将这些属性应用到底层的 InputBase 组件(可能带有样式),通常使用 JSX 展开属性语法:
如果你已经有一个作为对象的
props,并且你想在 JSX 中传递它,你可以使用...作为“展开”语法来传递整个 props 对象。
export const SearchInput = (props: React.ComponentProps<typeof InputBase>) => {
return (
<Box>
<FormControl sx={{ flexDirection: 'row', ml: '16px', width: '100%' }}>
<StyledInput placeholder="Search on Website" {...props} />
<Button sx={CONTAINED_BUTTON_STYLED} title="Search" />
</FormControl>
</Box>
)
}
然后你可以将其作为一个“普通”的InputBase使用:
function ParentComponent() {
return (
<SearchInput value="hello" onChange={(event) => console.log(event)} />
)
}
游乐场链接
