在render内部的if语句中执行内容

时间:2018-10-03 09:55:49

标签: reactjs react-native if-statement

我想执行if语句中的所有行,但不能

这是我的代码

import React, { Component } from 'react';
import { Text, View } from 'react-native';
class test extends Component {
  constructor() {
    super();
    this.state = { data: [] };
  }
  testFunction = () => {
    return (
      <View>
        <Text>Anything</Text>
      </View>
    );
  };

  render() {
    return (
      <View>{data.length > 0 ? <Text>Hi</Text> : this.testFunction() <Text>Hello</Text>}</View>
    );
  }
}
export default test;

我要执行(this.testFunction()和(<Text>Hello</Text>

谢谢

2 个答案:

答案 0 :(得分:1)

您可以这样操作:

render() {
  //Is data initialized?
  if (data.length > 0) 
    return (
      <Text>Hi</Text>
    )
  else 
    return (
      {this.testFunction()}
      <Text>Hello</Text>
    )
    
}

但是有更好的方法。例如,通过这种方式,您可以使渲染功能更整洁:

conditionalRender() {
  //Is data initialized?
  if (data.length > 0) 
    return (<Text>Hi</Text>)
  else 
    return (
      {this.testFunction()}
      <Text>Hello</Text>
    )  
}


render() {
  return (
    {this.conditionalRender)}
  )
}

答案 1 :(得分:0)

您可以修改函数,使其返回组件。

 condition1 () {
  // do something 
  return ( <FlatList
    data={[{key: 'a'}, {key: 'b'}]}
    renderItem={({item}) => <Text>{item.key}</Text>}
  />);
 }

 condition2 () {
  // do something 
  return ( <Text>Hello</Text>);
 }

然后在渲染器中调用

render() {
 return (
  <View> { data.length > 0 ? this.condition1() : this.condition2()} </View>
)}