![](/img/trans.png)
[英]How to render jsx only when a condition is true using react and typescript?
[英]How to render jsx in react with condition true and array mapping?
我想渲染某个条件为真的 JSX 并映射到一个数组。
下面是代码,
{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}
/>)
}
}
)
}
有一个错误说该表达式不是赋值或调用。 我该如何解决? 谢谢。
您需要为#Array.map
callback提供返回值。
此外,您应该为数组中的 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.