我有两个问题。我正在尝试编写一个组件来检查用户是否在移动设备上,如果他们是移动设备,则状态 isMobile 切换为 true(如果在桌面上,反之亦然)。
我已经找到了可以检查移动设备并且有效的地方,但是让它说“真或假”并且还克服了这是一个保留字,这让我非常困难。
非常感谢这里的任何帮助,这是我的代码:
//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>
);
}
}
提前感谢您的帮助
最佳答案
由于移动检查是同步的,因此您可以在构造函数中更新 isMobile
状态属性。另外,const { isMobile } = this.state;
是让isMobile
脱离状态的正确方法,它会解决你的this is a returned单词问题。
以下代码应该可以工作,但我还没有测试过:
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 .
关于javascript - React.js "this"是保留字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46778845/