gpt4 book ai didi

reactjs - 如何将现有的 InputProps 与子组件中的其他 InputProps 结合起来

转载 作者:行者123 更新时间:2023-12-02 00:12:08 25 4
gpt4 key购买 nike

我已经编写了具有自定义样式的 material-ui TextField 的自定义版本(我们称之为 CustTextField1)。我希望基于 CustTextField1 的样式开发另一个名为 CustTextField2 的自定义项。我已将 InputProps 应用到 CustTextField1,我希望将它们与我在那里应用的一些其他 InputProps 一起用于 CustTextField2。以下是代码的相关部分。应用于 CustTextField2 的 InputProps 出现(即密码眼睛图标)但似乎覆盖了已在 CustTextField1 中设置的 InputProps。非常感谢任何有关如何将两者结合起来的帮助。

function CustTextField1(props) {
return (
<TextField
InputProps={{
disableUnderline: true,
classes: {
root: textFieldStyle.rootInputStyle,
focused: textFieldStyle.focused,
disabled: textFieldStyle.disabled,
error: textFieldStyle.error
}
}}

{...props}
/>
)
}
function CustTextField2(props) {
return (
<CustTextField1
InputProps={{
endAdornment: (
<InputAdornment position="end">
<IconButton>
{showPassword ? <Visibility/> : <VisibilityOff/>}
</IconButton>
</InputAdornment>
),
...props.InputProps
}
}}

{...props}
/>
)
}

我希望 CustTextField1 中的 InputProps 样式与 CustTextField2 中的附加 InputProps 样式相结合。

!!已更新!!

代码沙箱(原始问题) - https://codesandbox.io/s/fervent-smoke-g8nsb

代码沙盒(解决方案) 衷心感谢下面 toutpt 的帖子 - https://codesandbox.io/s/stoic-mclean-9kh1r

最佳答案

当你想要继承时,你应该始终注意组合。所以首先你应该处理你想要覆盖的 Prop 。

在以下示例中,CustTextField1 将处理 InputProps 以添加基础并让用户覆盖它们。但是因为有 classes 这也是我需要处理的对象。

function CustTextField1({ InputProps, ...props }) {
const iprops = Object.assign({
disableUnderline: true,
}, InputProps, {
classes: Object.assign({
root: textFieldStyle.rootInputStyle,
focused: textFieldStyle.focused,
disabled: textFieldStyle.disabled,
error: textFieldStyle.error,
}, InputProps.classes || {})
});
return <TextField InputProps={iprops} {...props} />;
}

在您的示例中,您没有解构 Prop ,因此当您传播 Prop 时,您会完全覆盖 InputProps

 InputProps={}
{...props}

因此,如果 props 包含 InputProps,您需要执行两次:

InputProps={} // the one define by CustTextField1
...
InputProps={} // the one define by CustTextField2

关于reactjs - 如何将现有的 InputProps 与子组件中的其他 InputProps 结合起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58644872/

25 4 0
文章推荐: sql - 向密集秩函数添加条件子句(Where)
文章推荐: java - 相邻类中的 ActionListener 实现
文章推荐: java - SELECT * FROM BETWEEN AND