2017-10-16 68 views
0

我有兩個問題。我試圖編寫一個組件來檢查用戶是否在手機上,如果他們是手機,狀態isMobile切換爲真(如果在桌面上,反之亦然)。react.js「this」是一個保留字

我得到它,我可以檢查移動和工作,但得到它的說:「真的還是假的」,也征服了這是一個保留字被絆倒我非常糟糕。

這裏任何幫助majorly讚賞,這裏是我的代碼:

//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;