是否允许使用js添加react-jsx代码块?

时间:2018-03-27 13:59:49

标签: reactjs react-native

我所拥有的是具有某些条件的简单渲染功能。

class AwesomeTestClass {
  constructor() { /* constructor stuff */ }
  reder() {
    let OUT = (<Text> basic text 1 </Text>);

    if (someCondition) {
      OUT += (<Text> add some condition text </Text>);
    } else {
      OUT += (<Text> add other condition text </Text>);
    }

    OUT += (<Text> end of awesome text </Text>);

    return (
      <View>
        {OUT}
      </View>
    );
  }
}

我尝试完成以下输出:

<View>
<Text> basic text 1 </Text>
<Text> add some condition text </Text>
<Text> end of awesome text </Text>
</View>

我的错误如下:

  

RawText "[object Object][object Object]"必须包含在显式的<Text>组件中。

所以我想知道以下内容:

  • 有没有办法在js中的react-jsx变量上使用+=运算符,比如js和字符串一起使用?
  • 有没有办法在js中的react-jsx变量上使用+运算符,比如js和字符串一起使用?

如果没有,有办法吗?

  • 从String转换为JSX
  • 从JSX转换为String

我尝试过以下事情:

  • 使用JSX:

    // += visible at the top
    
    let OUT = (<Text>Awe</Text>);
    OUT = OUT + (<Text>some</Text>);
    

    错误输出:

      

    RawText "[object Object][object Object]"必须包含在显式的<Text>组件中。

  • 使用字符串:

    let OUT = "<Text>Awe</Text>";
    OUT = OUT + "<Text>some</Text>";
    
    let OUT = "<Text>Awe</Text>";
    OUT += "<Text>some</Text>";
    

    错误输出:

      

    RawText "<Text>Awe</Text><Text>some</Text>"必须包含在显式的<Text>组件中。

  • 使用字符串转换:

    let OUT = String(<Text>Awe</Text>);
    OUT = OUT + String(<Text>some</Text>);
    
    let OUT = String(<Text>Awe</Text>);
    OUT += String(<Text>some</Text>);
    

    错误输出:

      

    RawText "[object Object][object Object]"必须包含在显式的<Text>组件中。

  • 使用String Casting with String:

    let OUT = String(<Text>Awe</Text>);
    OUT = OUT + "<Text>some</Text>";
    
    let OUT = String(<Text>Awe</Text>);
    OUT += "<Text>some</Text>";
    

    错误输出:

      

    RawText "[object Object]<Text>some</Text>"必须包含在显式的<Text>组件中。

我为什么试试?
好吧,我不想将每个语句都移动到函数中。

2 个答案:

答案 0 :(得分:2)

也许只使用其中一个条件渲染策略,我会建议这样的事情:

return (
   <View>
     { someCondition ? 
        (<Text> add some condition text </Text>):
        (<Text> add other condition text </Text>)
     }
     <Text> end of awesome text </Text>
   </View>
);

请注意:https://reactjs.org/docs/conditional-rendering.html

答案 1 :(得分:2)

您可以将组件推送到数组中并渲染:

render() {
  let OUT = [(<Text key={1}> basic text 1 </Text>)];

  if (someCondition) {
    OUT.push(<Text key={2}> add some condition text </Text>);
  } else {
    OUT.push(<Text key={3}> add other condition text </Text>);
  }

  OUT.push(<Text key={4}> end of awesome text </Text>);

  return (
    <View>
      {OUT}
    </View>
  );
}

请注意,我在这种情况下添加了一个硬编码密钥。如果使用循环来渲染这些项,则需要一个键,因此如果动态添加或删除它们,则可以区分每个组件。不要将索引用作it's an anti-pattern的键。

相关问题