如何使用类名使用 Reactjs 呈现条件条件

我试图用一行替换下面的条件。classNames


我的问题是,我不确定编写代码的正确方法是什么,因为等等...div


我有以下代码:


有條件的

const { pageTitle, removeTitle = false } = props;   # destructuring


let result;


if(removeTitle){

  result = <div className="header-without-title">{pageTitle}</div>;

} else {

  result = <div className="header-with-title">{pageTitle}</div>;

}


return (<div className="result-title">{result});


};

如果不存在,我可以写这样的东西...div


const result = classNames({"header-without-title": removeTitle, "header-title": !removeTitle});


但我现在不确定我有,我会感激在这里得到一些帮助...div


一个解决方案之外将是非常有帮助的JSX


POPMUISE
浏览 85回答 3
3回答

慕的地6264312

return (&nbsp; &nbsp; <div className="result-title">&nbsp; &nbsp; &nbsp; &nbsp; <div className={`header-${removeTitle ? 'without-title' : 'with-title'}`}>{pageTitle}</div>&nbsp; &nbsp; </div>);或使用 https://github.com/JedWatson/classnamesreturn (&nbsp; &nbsp; <div className="result-title">&nbsp; &nbsp; &nbsp; &nbsp; <div className={classNames({ 'header-without-title': removeTitle, 'header-with-title': !removeTitle })}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {pageTitle}&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </div>);编辑:JSX之外的解决方案const result = (&nbsp; &nbsp; <div className={classNames({ 'header-without-title': removeTitle, 'header-with-title': !removeTitle })}>&nbsp; &nbsp; &nbsp; &nbsp; {pageTitle}&nbsp; &nbsp; </div>);return (&nbsp; &nbsp; <div className="result-title">&nbsp; &nbsp; &nbsp; &nbsp; {result}&nbsp; &nbsp; </div>);

白衣非少年

您可以只内联类名函数const { pageTitle, removeTitle = false } = props;const result = classNames({"header-without-title": removeTitle, "header-title": !removeTitle});return (&nbsp; <div className="result-title">&nbsp; &nbsp; <div className={result}>&nbsp; &nbsp; &nbsp; {pageTitle}&nbsp; &nbsp; </div>&nbsp; </div>););

拉风的咖菲猫

对此有几个答案。取决于每种情况React 中两个类之间的三元数:<div&nbsp;className={`header-${removeTitle&nbsp;?&nbsp;'without-title'&nbsp;:&nbsp;'with-title'}`}>类之间的三元或空在反应Java脚本中:<div&nbsp;className={removeTitle&nbsp;?&nbsp;'without-title'&nbsp;:&nbsp;null}>渲染类与否在 React Java 脚本和类型脚本中是三元的:<div&nbsp;className={...(removeTitle&nbsp;?&nbsp;{&nbsp;className:&nbsp;'without-title'&nbsp;}&nbsp;:&nbsp;{})}>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript