我创建了一个 Button
根据传递的 props 应用各种样式和类的组件。我还希望能够指定另一个 component
在诸如 Link
之类的 Prop 中来自react-router
。嵌套会导致各种问题(单击填充不起作用等)。
为此,我会接受 component
允许这样做的 prop,但是当未设置此 prop 时,我想使用默认的 html <button>
元素。
我经常使用||
当使用自定义组件做类似的事情时,但我似乎无法让它与默认的 html 元素一起工作。
class Button extends PureComponent {
render() {
const {
size,
width,
variation,
disabled,
loading,
position,
children,
className,
component,
...otherProps
} = this.props;
// Here lies the problem, "button" is not defined here, how to use the default html element while not loosing props specified below?
const Button = component || button;
return (
<Button
className={classnames(
"BUTTON",
{
[`BUTTON-size--${size}`]: size,
[`BUTTON-width--${width}`]: width,
[`BUTTON-variation--${variation}`]: variation,
[`BUTTON-position--${position}`]: position,
"BUTTON-state--disabled": disabled,
"BUTTON-state--loading": loading
},
className
)}
disabled={disabled || loading}
{...otherProps}
>
{children}
</Button>
);
}
}
最佳答案
查看material-ui-next
ButtonBase我注意到这个问题有一个非常简单的方法,即只需执行以下操作:
class Button extends PureComponent {
render() {
const {
size,
width,
variation,
disabled,
loading,
position,
children,
className,
component,
...otherProps
} = this.props;
const Component = component;
return (
<Component
className={classnames(
"BUTTON",
{
[`BUTTON-size--${size}`]: size,
[`BUTTON-width--${width}`]: width,
[`BUTTON-variation--${variation}`]: variation,
[`BUTTON-position--${position}`]: position,
"BUTTON-state--disabled": disabled,
"BUTTON-state--loading": loading
},
className
)}
disabled={disabled || loading}
{...otherProps}
>
{children}
</Component>
);
}
}
Button.propTypes = {
component: PropTypes.oneOfType([PropTypes.node, PropTypes.oneOf(["a", "button"])]),
// ... ohter
};
Button.defaultProps = {
component: "button",
// ... other
};
export default Button;
请注意,我只是使用 component
属性,默认值为“button”
。
关于javascript - 在 const 声明中使用 React prop 或 html 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47534223/