Mow*_*zer 8 css jsx media-queries reactjs
如何在Reactjs中执行以下CSS媒体查询?
.heading {
text-align: right;
/* media queries */
@media (max-width: 767px) {
text-align: center;
}
@media (max-width: 400px) {
text-align: left;
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试了以下操作,但是它引发了语法错误并且无法编译。
heading: {
textAlign: 'right',
@media (maxWidth: '767px') {
textAlign: 'center';
}
@media (maxWidth: '400px') {
textAlign: 'left';
}
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*ero 33
Ferit给出的答案非常有用,但是,这只是类组件中的示例,但将其应用于功能组件通常很困难或麻烦,而且有时将功能组件转换为函数组件会出现问题。第一课,这里我留下使用Hooks的例子
import React, { useState, useEffect } from 'react';
const App = () => {
const [matches, setMatches] = useState(
window.matchMedia("(min-width: 768px)").matches
)
useEffect(() => {
window
.matchMedia("(min-width: 768px)")
.addEventListener('change', e => setMatches( e.matches ));
}, []);
return (
<div >
{matches && (<h1>Big Screen</h1>)}
{!matches && (<h3>Small Screen</h3>)}
</div>
);
}
export default App;
Run Code Online (Sandbox Code Playgroud)
fer*_*rit 22
你可以在 React 中进行媒体查询:
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props)
this.state = { matches: window.matchMedia("(min-width: 768px)").matches };
}
componentDidMount() {
const handler = e => this.setState({matches: e.matches});
window.matchMedia("(min-width: 768px)").addListener(handler);
}
render() {
return (
<div >
{this.state.matches && (<h1>Big Screen</h1>)}
{!this.state.matches && (<h3>Small Screen</h3>)}
</div>
);
}
}
export default App;
Run Code Online (Sandbox Code Playgroud)
https://repl.it/repls/MemorableThoseLevels
小智 12
如果您有特殊情况,当您需要在 React 应用程序中获取媒体查询结果时(例如,您想在移动版本中显示某个组件),您可以使用诸如react-responsive或react-media-hook 之类的助手。
Nik*_*wda 12
在reactjs项目中另一种编写媒体查询的方法:
style.js 文件:
root: {
background: "white",
"@media (max-width: 1920px)": {
background: "red",
}
}
Run Code Online (Sandbox Code Playgroud)
style.css 文件:
.root: {
background: "white";
@media (max-width: 1920px) {
background: "red";
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢
您不能内联设置媒体查询。您将需要创建一个单独的CSS样式表,然后导入该样式表。
因此,以下代码将放入一个新styles.css文件中。
text-align: right;
/* media queries */
@media (max-width: 767px) {
text-align: center;
}
@media (max-width: 400px) {
text-align: left;
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以将新的CSS样式文件导入到react文件中。例如,您可以将其添加import './styles.css'到App.jsx文件的顶部(假设它们都在根级别),也可以将其直接导入到特定的React组件文件中。
小智 5
如果您习惯使用 css,则可以使用 styled-components。它看起来像这样。
import React from 'react';
import Styled from "styled-components";
function YourComponent() {
const heading = Styled.h1`
Text-align:right;
@media (max-width: 767px) {
text-align: center;
}
@media (max-width: 400px) {
text-align: left;
}
`;
return(
<>
<heading>This is my heading</heading>
</>
)
}
Run Code Online (Sandbox Code Playgroud)
如果你有很多样式需要做,你可以在另一个 js 文件中做你的样式并根据需要导入每个样式。如果您这样做,请不要忘记导出您的样式。
| 归档时间: |
|
| 查看次数: |
5763 次 |
| 最近记录: |