如何连接两个JSX片段或变量或字符串和组件(在Reactjs中)?

Sep*_*phy 26 concatenation 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;
}
Run Code Online (Sandbox Code Playgroud)

我有一条线,我想在某些条件下"连接"前面的一些div.什么是正确的语法?我试过括号,括号,加号......它们似乎都不起作用......

谢谢

And*_*yco 46

使用数组:

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;
}
Run Code Online (Sandbox Code Playgroud)

或者使用片段:

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;
}
Run Code Online (Sandbox Code Playgroud)

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

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


Pet*_*vin 11

对于React Native,我更喜欢这种技术:

  1. 亲:与阵列技术相比,您不必人为地创建键
  2. con:需要包含元素的开销(例如,View,下方)
jsx = <Text>first</Text>;
jsx = <View>{jsx}<Text>second</Text></View>;
Run Code Online (Sandbox Code Playgroud)


Top*_*ter 10

你可以使用空标签,我的意思是,<></>,只要你不想要任何额外的Container-Element(例如<View>),如下所示:

  render() {
    return (
      <>
        <Text>First</Text>

        <Text>Second</Text>
      </>
    );
  }
Run Code Online (Sandbox Code Playgroud)

例子:

import React from 'react'
import { View, Text } from 'react-native'

import Reinput from 'reinput'

export default class ReinputWithHeader extends Reinput {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <>
        <View style={{backgroundColor: 'blue', flexDirection: 'row', alignSelf: 'stretch', height: 20}}>
          <Text>Blue Header</Text>
        </View>

        {super.render()}
      </>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

注意:我测试过,它也适用react-native;另见片段

预览:

在此处输入图片说明


wei*_*all 6

可以使用数组并在那里推送jsx代码。例如:

   function App() {

      function cells() {
        const size = 10;
        const cells = [];
        for (let i=0; i<size; i++) {
          cells.push(
            <tr>
              <td>Hello World</td>
            </tr>
          )
        }
        return cells;
      }

      return (
        <table>
          <tbody>
            {cells()}
          </tbody>
        </table>
      );
    }
Run Code Online (Sandbox Code Playgroud)