简体   繁体   English

如何渲染 jsx 以响应条件 true 和数组映射?

[英]How to render jsx in react with condition true and array mapping?

I want to render a JSX with some condition being true and map through an array.我想渲染某个条件为真的 JSX 并映射到一个数组。

below is the code,下面是代码,

{this.props.variables &&
     this.props.variable.map((variable, index) => {
         let element;
         if (variable.anchor) {
             element = document.querySelector(variable.anchor);
         }
         this.box_ref.current && element && (// error here
             <Childcomponent
                 element1={this.box_ref.current}
                 anchor={variable.anchor}
              />)
          }
      }
  )
}

There is an error saying that the expression is not an assignment or a call.有一个错误说该表达式不是赋值或调用。 how can I fix it?我该如何解决? thanks.谢谢。

You need to provide a return value for #Array.map callback .您需要为#Array.map callback提供返回值。

Also, you should provide unique keys to React elements within an array:此外,您应该为数组中的 React 元素提供唯一键:

<>
  {this.props.variables &&
    this.props.variable.map((variable, index) => {
      let element;
      if (variable.anchor) {
        element = document.querySelector(variable.anchor);
      }
//       v Add return statement
      return (
        this.box_ref.current &&
        element && (
          <Childcomponent
            key={index}
            element1={this.box_ref.current}
            anchor={variable.anchor}
          />
        )
      );
    })}
</>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM