I have a bunch of react ponents that I'm hoping I can use for both web and native. The way I am trying to do that is like so:
React.createClass({
getInitialState: function(){
return {isMobile: <some way of tell is native or web>};
},
render: function(){
if(this.state.isMobile){
return <SomeIosComponent/>
}
else{
return <div/>
}
}
});
I'd like to be able to do this so I can keep the logic the same for something that appears to be the same on web and native, is this possible? Could it be as simple as {isMobile: (window ? false : true)}
? Or does window exist in native so there is a way to define globals within a local scope for some odd reason?
I know this goes against the React philosophy of "Learn once, write anywhere".
I have a bunch of react ponents that I'm hoping I can use for both web and native. The way I am trying to do that is like so:
React.createClass({
getInitialState: function(){
return {isMobile: <some way of tell is native or web>};
},
render: function(){
if(this.state.isMobile){
return <SomeIosComponent/>
}
else{
return <div/>
}
}
});
I'd like to be able to do this so I can keep the logic the same for something that appears to be the same on web and native, is this possible? Could it be as simple as {isMobile: (window ? false : true)}
? Or does window exist in native so there is a way to define globals within a local scope for some odd reason?
I know this goes against the React philosophy of "Learn once, write anywhere".
Share Improve this question edited Jul 30, 2015 at 19:27 Christian Grabowski asked Jul 30, 2015 at 19:21 Christian GrabowskiChristian Grabowski 2,8924 gold badges35 silver badges57 bronze badges 2- Perhaps I'm missing something, but wouldn't your code need to know at a higher level since you need to include 'react-native' or 'react' but not both – Ed Ballot Commented Jul 30, 2015 at 19:51
- I could do that at build time with gulp. Although I guess I could also have it require files that just have the ponents that are named the same and just added at build time. – Christian Grabowski Commented Jul 30, 2015 at 19:58
1 Answer
Reset to default 5Like you said, this goes against the React philosophy, so I wouldn't remend it.
However, there is a way to determine which React
you're using if you really want to use this method. This might feel a bit hacky, but React Native has many properties that React does not. So when you write your ponents, you can check if React.View
exists. If it does, you're using React Native. Otherwise, you're using the web version.
React.createClass({
getInitialState: function(){
return {isMobile: React.View !== undefined };
},
render: function(){
if(this.state.isMobile){
return <SomeIosComponent/>
}
else{
return <div/>
}
}
});
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745370648a4624779.html
评论列表(0条)