我有一个要渲染的组件,它会根据传入的 props 进行不同的渲染:
const Label = ({ data, attribute, style, link }) => (
<Link to={link} style={style}>{data ? `${data[attribute]}` : ''}</Link>
);
style
和 link
Prop 是可选的,所以我想根据它们是否存在以不同方式呈现组件 - 我能想到的唯一方法就是这样,但是 jsx 是错误的。 React 中的最佳实践是什么?谢谢。
const Label = ({ data, attribute, style, link }) => (
if(link && style) {
<Link to={link} style={style}>{data ? `${data[attribute]}` : ''}</Link>
} else if (link) {
<Link to={link}>{data ? `${data[attribute]}` : ''}</Link>
}
//...
);
最佳答案
我会做这样的事情:
const Label = ({ data, attribute, style, link }) => {
if (link) {
return (
<Link to={link} style={style}>{data ? `${data[attribute]}` : ''}</Link>
);
}
// ...
};
你应该能够安全地将 undefined 作为 style
属性传递
关于javascript - 在 React 中,如何根据传入的 props 动态渲染组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46481545/