gpt4 book ai didi

reactjs - 了解如何使 React 网站移动友好

转载 作者:行者123 更新时间:2023-12-02 19:36:53 24 4
gpt4 key购买 nike

我一直在研究 react-responsive了解如何使网站适合移动设备。本质上,我想要做的是从一个函数中传递一个值,该函数测试查看屏幕的大小是否像手机一样。实际上是从 react-responsive 的文档中偷来的,我在一个名为 Mobile.js 的文件中有一个函数,如下所示:

const Mobile = () => {
const mobile = useMediaQuery({ query: '(max-width: 1000px)' })
return (
<div>
{mobile && <p>You are sized like a mobile phone</p>}
</div>
);
}

但是,我想要做的是将 bool 值“mobile”传递到其他 js 文件中的其他类中,然后我可以根据此 bool 值的值使用不同的 CSS 类名。

我有 3 个具体问题。

  1. 如何从要使用的 Mobile 函数返回 bool 值 mobile?

  2. 我将如何访问这个返回的 bool 值?

  3. 如何根据此 bool 值更改 div 的类名?

Web 开发(尤其是 React)的新手,这些问题看起来 super 简单且容易解决,但出于某种原因,我似乎无法通过自己的在线研究弄明白。会喜欢直接的帮助和一些我可以学到更多的资源。非常感谢!

对我来说,在一个完美的世界中,正确的代码在我的脑海中应该是这样的。不确定我离我有多远,但我希望这可能对我的想法有一些指导。

在函数文件中,

// FILE Mobile.js
const Mobile = () => {
const mobile = useMediaQuery({ query: '(max-width: 1000px)' })
return (
{ mobile } // how to return a value?
);
}

export default Mobile;

在另一个文件中,

// FILE OtherClass.js
import Mobile from './Mobile';
class OtherClass extends Component {

constructor(props) {
super(props);

this.state = { mobile: <Mobile /> } // how to access the returned value?
}


render() {
return (
<div>
{this.state.mobile && <div className="text-mobile">} // how to change the className depending on value?
{!this.state.mobile && <div className="text-desktop">}
blah blah blah blah blah
</div>
</div>
);
}
}

最佳答案

感谢您的提问,欢迎来到 React 开发!

我可以帮到你

How would I return the boolean mobile from the Mobile function to be used?

How would I access this returned boolean?

因为你正在调用一个钩子(Hook)useMediaQuery,你还需要一个钩子(Hook)来重用它并返回它的值:

function useIsMobile() {
const isMobile = useMediaQuery({ query: '(max-width: 1000px)' });
return isMobile
}
//Then you can share this logic in other components
function Component1(){
const isMobile = useIsMobile()
...
}
function Component2(){
const isMobile = useIsMobile()
...
}

请注意,您不能在 class 组件中使用 hooks。

How would I change the className of a div depending on the value of this boolean?

这很简单:

function Component(){
const isMobile = useIsMobile()
const className = isMobile ? 'mobile-class' : 'desktop-class'
return <div className={className}>...</div>
}

如果您需要更复杂的类名逻辑,您可以查看 the package classnames这使得激活/停用类变得非常容易。

关于reactjs - 了解如何使 React 网站移动友好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60911380/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com