【问题标题】:execute content in the if statement inside render [duplicate]在渲染内的if语句中执行内容[重复]
【发布时间】:2019-03-08 12:40:58
【问题描述】:

我想执行 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()) 和 (&lt;Text&gt;Hello&lt;/Text&gt;)

谢谢

【问题讨论】:

  • 请提供您的完整组件代码
  • import React, { Component } from 'react'; import { Text, View} from 'react-native'; class test extends Component { constructor() { super(); this.state = { data: [], }} testFunction = () =&gt; { return ( &lt;View&gt;&lt;Text&gt;Anything&lt;/Text&gt;&lt;/View&gt; ) }render() { return ( &lt;View&gt; {data.length &gt; 0 ? &lt;Text&gt;Hi&lt;/Text&gt; : this.testFunction() &lt;Text&gt;Hello&lt;/Text&gt; } &lt;/View&gt; );} } export default test;

标签: reactjs react-native if-statement


【解决方案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)}
  )
}

【讨论】:

    【解决方案2】:

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

     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>
    )}
    

    【讨论】:

    • 我想在&lt;Text&gt;Hi&lt;/Text&gt;之后和:之前添加一些东西
    • 您可以将它们全部放在另一个函数中。请参阅我修改后的答案。
    • 我有一个问题.. 我使用FlatListFlatList 不显示内部功能
    • FlatList 不显示是什么意思?
    • 在函数内部添加了一个 FlatList 组件。请参考
    猜你喜欢
    • 1970-01-01
    • 2016-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多