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