我有兩個問題。我試圖編寫一個組件來檢查用戶是否在手機上,如果他們是手機,狀態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>
);
}
}
預先感謝您的幫助
那麼'const isMobile = {this.state.isMobile}'是一個語法錯誤。你的意思是'const isMobile = this.state.isMobile;'或類似'const isMobile = {propertyName:this.state.isMobile};'? – Bergi
同樣,你做'state = {isMobile:true};'但它應該是'this.state = {isMobile:true};'。 –