2017-10-16 6 views
0

私は2倍の質問があります。私は、ユーザーがモバイルであるかどうかをチェックするコンポーネントを作成しようとしています。モバイルの場合は、isMobileがtrueに切り替わります(デスクトップの場合はその逆)。react.js "this"は予約語です

私はモバイルで調べることができますが、それはうまくいっていますが、それが「真実か偽」かというと、を征服することは予約語です私はかなり悪いです。

ここで任意の助けがすぎなかっ高く評価され、ここに私のコードは次のとおりです。

//this part will be imported via a component. Need to check and make sure how to update state via component. 
const checkIfMobile = { 
    Android: function() { 
    return navigator.userAgent.match(/Android/i); 
    }, 
    BlackBerry: function() { 
    return navigator.userAgent.match(/BlackBerry/i); 
    }, 
    iOS: function() { 
    return navigator.userAgent.match(/iPhone|iPad|iPod/i); 
    }, 
    Opera: function() { 
    return navigator.userAgent.match(/Opera Mini/i); 
    }, 
    Windows: function() { 
    return navigator.userAgent.match(/IEMobile/i); 
    }, 
    any: function() { 
    return (
     checkIfMobile.Android() || 
     checkIfMobile.BlackBerry() || 
     checkIfMobile.iOS() || 
     checkIfMobile.Opera() || 
     checkIfMobile.Windows() 
    ); 
    } 
}; 

//testing out a function to a get a boolean (true or false) 
const trueOrFalse =() => { 
    console.log('hi', checkIfMobile); 
}; 

export default class App extends Component { 
    constructor() { 
    super(); 
    //the state "isMobile" would update the boolean changing the test when user is using mobile device 
    state = { isMobile: true }; 
    } 
    render() { 
    //an if/else statement to see if it will detect mobile. It does however I have the problem of "this is a reserved word" 
    if (checkIfMobile.any()) { 
     console.log("it's mobile"); 
    } else { 
     trueOrFalse(); 
    } 

    const isMobile = { this.state.isMobile }; 

    return (
     <div> 
     <ChromePluginNotice /> 

     <Banner isMobile={isMobile} /> 
     <Content isMobile={isMobile} /> 
     <Footer /> 
     </div> 
    ); 
    } 
} 

あなたの助けに前もって感謝

+3

まあ、 'const isMobile = {this.state.isMobile}'は構文エラーです。 'const isMobile = this.state.isMobile;'のようなものか、 'const isMobile = {propertyName:this.state.isMobile};'のようなものでしたか? – Bergi

+1

同様に、 'state = {isMobile:true};'を実行しますが、 'this.state = {isMobile:true};'でなければなりません。 –

答えて

2

へあなたはモバイルCですheckが同期している場合は、コンストラクタのisMobile状態プロパティを更新できます。また、const { isMobile } = this.state;isMobileを状態から抜き出す正しい方法であり、はこれを予約語に解決します。

次のコードは動作するはずですが、私はそれをテストしていない:

export default class App extends Component { 
    constructor() { 
    super(); 

    // set the isMobile prop in state 
    this.state = { isMobile: checkIfMobile.any() }; 
    } 
    render() { 
    const { isMobile } = this.state; // destructure isMobile to variable 

    return (
     <div> 
     <ChromePluginNotice /> 

     <Banner isMobile={isMobile} /> 
     <Content isMobile={isMobile} /> 
     <Footer /> 
     </div> 
    ); 
    } 
} 

:代わりに車輪の再発明、そしてあなた自身の携帯電話が検出作成するのではなく、既存のモジュールを、このように使用してみてくださいbowserとします。

+0

ようこそ@sthig :) –

2

変更

const isMobile = { this.state.isMobile }; 

const { isMobile } = this.state;