![](/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.