如何连接两个JSX片段或变量或字符串和组件(在Reactjs中)? [英] How to concatenate two JSX fragment or variables or string and component (in Reactjs)?

查看:172
本文介绍了如何连接两个JSX片段或变量或字符串和组件(在Reactjs中)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道JSX可能会产生很大的误导性,因为它看起来像字符串,而实际上不是,因此,即使我们不是真正在操纵字符串,它也是问题中的字符串"一词.

这是一个代码示例(显然是错误的):

let line = <Line key={line.client_id} line={line}/>;
if(line.created_at) {
    return <div className="date-line"><strong>{line.created_at}</strong></div> + line;
} else {
    return chat_line;
}

我有一行,在某些情况下,我想在其前面连接"一些div.正确的语法是什么? 我已经尝试过括号,方括号和加号...它们似乎都不起作用...

谢谢

解决方案

使用数组:

let lineComponent = <Line key={line.client_id} line={line}/>;
if (line.created_at) {
  return [
    <div key="date" className="date-line"><strong>{line.created_at}</strong></div>,
    lineComponent,
  ];
} else {
  return chat_line;
}

或使用片段:

import createFragment from "react-addons-create-fragment";

let lineComponent = <Line key={line.client_id} line={line}/>;
if (line.created_at) {
  return createFragment({
    date: <div className="date-line"><strong>{line.created_at}</strong></div>,
    lineComponent: lineComponent,
  });
} else {
  return chat_line;
}

在两种情况下,您都必须提供React的密钥.如果是数组,则直接在元素上设置键.关于片段,您提供key:element对.

注意: render方法返回时,只能返回单个元素或NULL.在这种情况下,提供的示例无效.

I know JSX can be very misleading because it looks like strings and it is not, thus the "string" term in the question, even if we are not really manipulating strings.

Here is a code example (wrong, obviously):

let line = <Line key={line.client_id} line={line}/>;
if(line.created_at) {
    return <div className="date-line"><strong>{line.created_at}</strong></div> + line;
} else {
    return chat_line;
}

I have a line, and I want to "concatenate" some divs in front of it under certain conditions. What would be the proper syntax? I've tried parenthesis, brackets, plus sign... None of them seem to work...

thanks

解决方案

Use arrays:

let lineComponent = <Line key={line.client_id} line={line}/>;
if (line.created_at) {
  return [
    <div key="date" className="date-line"><strong>{line.created_at}</strong></div>,
    lineComponent,
  ];
} else {
  return chat_line;
}

Or use fragments:

import createFragment from "react-addons-create-fragment";

let lineComponent = <Line key={line.client_id} line={line}/>;
if (line.created_at) {
  return createFragment({
    date: <div className="date-line"><strong>{line.created_at}</strong></div>,
    lineComponent: lineComponent,
  });
} else {
  return chat_line;
}

In both cases, you have to provide keys for React. In case of array, you set key directly on element. Regarding fragments, you provide key:element pairs.

NOTE: When returning from render method, you can only return single element, or NULL. Examples provided are invalid in that case.

这篇关于如何连接两个JSX片段或变量或字符串和组件(在Reactjs中)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆