[英]React Custom Component Styling
所以我为经常使用的路由器链接创建了一个自定义组件,这是它的 JS 文件的外观:
import { Link } from "react-router-dom";
import styles from "./LNLink.module.css";
class LNLink extends Component {
render() {
return (
<Link className={styles.LNLink} to={this.props.to}>
{this.props.text}
</Link>
);
}
}
export default LNLink;
现在,这个组件在我的 Login.js 中被调用,例如:
<LNLink
to="/sign-up"
text="Sign up"
className={styles.loginSignUpLink}
/>
现在这一切在功能上都可以正常工作,问题是在 Login.js, className={styles.loginSignUpLink}
中分配的类没有被分配,没有被分配和覆盖,它们根本不在浏览器检查中,为什么会这样案子?
奖励问题:是否可以在<LNLink>
和它的结束标签之间发送它而不是传递一个text
道具,并以相同的方式使用它?
非常感谢
要回答问题的额外部分,您可以在<LNLink>
之间传递任何您想要的内容,然后使用this.props.children
在此组件中呈现它
<LNLink>Whatever you want here (text, JSX, other components)</LNLink>
return (
<Link className={styles.LNLink} to={this.props.to}>
{this.props.children}
</Link>
);
我认为您还应该使用className
作为 LNLink 的道具。 children
可以得到标签内的任何东西。
class LNLink extends Component {
render() {
return (
<Link className={this.props.className} to={this.props.to}>
{this.props.children}
</Link>
);
}
}
export default LNLink;
<LNLink
to="/sign-up"
className={styles.loginSignUpLink}
/>
Sign up
</Link>
好吧我想通了,问题是我没有使用传递给组件的样式,修复很简单,只需在组件上添加this.props.className
作为样式,所以在我的LNLink.js
中我修改了className
看起来如下:
className={classNames(styles.LNLink, this.props.className)}
现在我正在使用classNames
package 因为它看起来更干净,因为我使用的是 css 模块,但如果你不是,你可以输入如下:
className={`${styles.LNLink} ${props.className`}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.