html渲染中可选部件的最佳实践

时间:2017-06-16 08:55:36

标签: reactjs

我想知道有条件地渲染项目列表的好方法。基本上我想渲染一条警告信息,如果有警告,我想渲染消息以包含所有问题的列表,这是我目前的方法:

text = (
	<div>Orange fields are not mandatory, are you sure you want to submit without :
		<ul>
			{(() => {
				if (e.infos.error === "warning")
					return <li>informations</li>
			})()}
			{(() => {
				if (e.links.error === "warning")
					return <li>links</li>
			})()}
			{(() => {
				if (e.file.error === "warning")
					return <li>file</li>
			})()}
		</ul>
	</div>);

那很难看,但我想测试一下,所以我采取的另一种方法就是这样:

function optionalWarning(props) {
  if (props.error === "warning")
    return <li>{props.message}</li>;
  return null;
}

....

text = (
	<div>Orange fields are not mandatory, are you sure you want to submit without :
		<ul>
      <optionalWarning error="e.infos.error" message="informations" />
      <optionalWarning error="e.links.error" message="links" />
      <optionalWarning error="e.file.error" message="file" />
		</ul>
	</div>);

这更漂亮,但我不喜欢我必须制作外部函数才能做到这一点,我想最好的做法是第二个,但还有其他方法吗?

3 个答案:

答案 0 :(得分:2)

使用logical operators - 只有在左侧是真实的情况下才会使用这些陈述的右侧。

否则,如果左侧是falseundefinednull,则React不会渲染任何内容。

<div>Orange fields are not mandatory, are you sure you want to submit without :
  <ul>
    {e.infos.error === "warning" && <li>informations</li>}
    {e.links.error === "warning" && <li>links</li>}
    {e.file.error === "warning" && <li>file</li>}
  </ul>
</div>

当您的支票失败时,您必须始终确保falseundefinednull结果 - 例如如果您使用{list.length && <Something/>}检查列表的长度,则当列表为空时,这将评估为0,而React会将其呈现为文本,而像{list.length > 0 && <Something/>}这样的检查将按预期工作。

答案 1 :(得分:1)

ternary operator使用conditional rendering,在JSX中编写条件会很容易。

像这样:

<div>Orange fields are not mandatory, are you sure you want to submit without :
    <ul>

        {e.infos.error === "warning" ? <li>informations</li> : null }

        {e.links.error === "warning" ? <li>links</li> : null}

        {e.file.error === "warning" ? <li>file</li> : null}

    </ul>
</div>

答案 2 :(得分:0)

我会选择:

<ul>
  { e.infos.error === "warning" && <li>informations</li> }
  { e.links.error === "warning" && <li>links</li> }
  { e.file.error === "warning" && <li>file</li> }
</ul>
相关问题