Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何在react中有条件地添加组件_Reactjs_React Native - Fatal编程技术网

Reactjs 如何在react中有条件地添加组件

Reactjs 如何在react中有条件地添加组件,reactjs,react-native,Reactjs,React Native,我的代码看起来像这样 <iOSOnlyComponent> ..... ..... ..... </iOSOnlyComponent> 但是我遇到了一个语法错误您应该执行以下操作(未经测试的代码) render(){ const helloMessageIOS=你好,JSX; 返回( {isIOS&&helloMessageIOS} ); } 如果iOSOnlyComponent组件很大,您只需将其添加到函数中并从中返回即可 可能如下所示(未测试代码) render(

我的代码看起来像这样

<iOSOnlyComponent>
.....
.....
.....
</iOSOnlyComponent>

但是我遇到了一个语法错误

您应该执行以下操作(未经测试的代码)

render(){
const helloMessageIOS=你好,JSX;
返回(
{isIOS&&helloMessageIOS}
);
}
如果iOSOnlyComponent组件很大,您只需将其添加到函数中并从中返回即可

可能如下所示(未测试代码)

render(){
返回(
{isIOS&&{this.displayComponent()}
);
}
displayComponent(){
回复你好,JSX;
}

使用条件呈现

 renderIosComp(){
    if(isIOS){   //use your variable here ideally props or state should be used
      return(<iOSOnlyComponent>
              .........
             ..........
            <iOSOnlyComponent />);
    }
    else{
         return(<div></div>);
    }
 }
renderIosComp(){
如果(isIOS){//请在此处使用变量,最好使用props或state
返回(
.........
..........
);
}
否则{
return();
}
}
在渲染方法中调用此函数

render(){
   return(<div>  
         .......
         ......
          {this.renderIosComp()}
          </div>);
}
render(){
报税表(
.......
......
{this.renderIosComp()}
);
}

如果条件呈现使您的组件过于复杂,您只需将其分成两个文件,分别命名为
myComponent.android.js
myComponent.ios.js
,然后从“/myComponent”导入myComponent即可。


React将自动选择正确的文件。

您是否可以共享您的
渲染
方法,其中您希望有条件地渲染
iOSOnlyComponent
?渲染方法非常庞大。我只想在iOS上使用KeyboardAvoidgView好的,你能分享你的错误吗?你可以很容易地把它一分为二
render() {
    return (
    <View >
       {isIOS  && {this.displayComponent()}   }
    </View >
  );
}


displayComponent() {
   return <iOSOnlyComponent> Hello, JSX! </iOSOnlyComponent>;
}
 renderIosComp(){
    if(isIOS){   //use your variable here ideally props or state should be used
      return(<iOSOnlyComponent>
              .........
             ..........
            <iOSOnlyComponent />);
    }
    else{
         return(<div></div>);
    }
 }
render(){
   return(<div>  
         .......
         ......
          {this.renderIosComp()}
          </div>);
}