使用React将多个html元素存储在变量中

时间:2018-09-25 15:23:32

标签: html reactjs jsx

我有一些重复的代码,这些代码在React组件中呈现了一些html。我想将重复的html元素存储在变量中并返回它们,但无法执行此操作。

agent.conv()

理想情况下,我想要这样的东西:

const renderAddress = event => {
  if (event.venue.address.address_2) {
    return (
      <address>
        {event.venue.address.address_2}
        <br />
        {event.venue.address.address_1}
        <br />
        {event.venue.address.city}
        <br />
        {event.venue.address.postal_code}
      </address>
    )
  } else {
    return (
      <address>
        {event.venue.address.address_1}
        <br />
        {event.venue.address.city}
        <br />
        {event.venue.address.postal_code}
      </address>
    )
  }
}

2 个答案:

答案 0 :(得分:2)

您理想的方法似乎是构成最后<address>元素的好方法。您可以使用Fragments来实现此目的,因为问题/错误将围绕baserenderAddress(event)的内容,因此需要使用一些元素进行包装,以避免尝试呈现{ {1}}。使用{event.venue.address.address_1}可以渲染React.Fragment,同时避免引入其他渲染的包装元素:

base

这是基本的example

注意: const renderAddress = event => { const base = ( <React.Fragment> {event.venue.address.address_1} < br /> {event.venue.address.city} < br /> {event.venue.address.postal_code} </React.Fragment> ); if (event.venue.address.address_2) { return ( <address> {event.venue.address.address_2} <br /> {base} </address> ); } else { return ( <address> {base} </address> ); } }; 仅在React 16.2+版中可用。

希望有帮助!

答案 1 :(得分:1)

我喜欢JSX及其操作方式,因此,我也想发布答案。

使用易于操作的数组和本机JSX渲染的组合,就像这样...

const renderAddress = event => {
  var address_pieces = [];

  if (event.venue.address.address_2) {
    address_pieces.push(event.venue.address.address_2);
  }

  address_pieces.push(event.venue.address.address_1);
  address_pieces.push(event.venue.address.city);
  address_pieces.push(event.venue.address.postal_code);

  return (
    <address>
      {address_pieces.map(address_piece => {
        return (
          <span>
            {address_piece}
            <br />
          </span>
        );
      })}
    </address>
  );
};

这将删除代码中的多余部分,并为您提供一些新的JS工具,例如map()

我还在此处编写了完整的工作示例:https://codesandbox.io/s/r1w60ozo3o