css - 在 react js 中为不同的页面应用不同的背景图片
问题描述
我想为登录页面和主页设置不同的背景图片。如果我将图像应用于正文标签,那么它将应用于所有页面。当我将它应用到特定的登录页面时,它可以工作,但它只会根据登录页面的宽度和高度来应用。
应用于 index.css 中的正文
body{
background-image: url("http://web3canvas.com/wp-content/uploads/2014/02/littlevisuals-high-quality-hd-banner-images-stock-photos-free-laptop-topview-download.jpg");
background-size: cover;
}
这是登录页面
这是主页
我只想要登录页面中的背景图片。
我已将该图像应用到登录页面的最外层 div 中。
<div className={classes.body}>
<React.Fragment>
<CssBaseline />
<main className={classes.layout}>
<Paper className={classes.paper}>
<Avatar className={classes.avatar}>
<LockIcon />
</Avatar>
<Typography variant="headline" className={classes.color}>Sign in</Typography>
<form onSubmit={this.handleSubmit}>
<FormControl margin="normal" required fullWidth>
<Field
component={renderTextField}
label="Email"
id="email"
name="email"
value={email}
onChange={this.handleChange}
fullWidth
/>
</FormControl>
<FormControl margin="normal" required fullWidth>
<Field
value={password}
onChange={this.handleChange}
name="password"
type="password"
id="password"
component={renderTextField}
label="Password"
className={classes.color}
fullWidth />
</FormControl>
<Button type="submit"
disabled={pristine || submitting}
fullWidth
variant="outlined"
color="secondary"
className={classes.submit}
>
Submit
</Button>
</form>
<Button
fullWidth
variant="outlined"
color="primary"
className={classes.submit}>
<Link to="/register">
New User ? Register Here
</Link>
</Button>
<SocialButton
fullWidth
variant="raised"
color="primary"
className="btn btn-danger form-control"
provider='google'
appId='967209745915-djav2bq5ic5r4ad9on3itp5a079s1ruu.apps.googleusercontent.com'
onLoginSuccess={this.handleSocialLogin}
onLoginFailure={this.handleSocialLoginFailure}
key={'google'}
>
Login with Google
</SocialButton>
</Paper>
</main>
</React.Fragment>
</div>
帮我找人。
编辑 -
我正在使用材质 UI
这是完整的登录页面代码。
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { userActions } from '../../_actions';
import '../../index.css';
import axios from 'axios';
import { history } from '../../_helpers/history';
import SocialButton from '../../SocialButton';
import compose from 'recompose/compose';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Avatar from '@material-ui/core/Avatar';
import Button from '@material-ui/core/Button';
import CssBaseline from '@material-ui/core/CssBaseline';
import FormControl from '@material-ui/core/FormControl';
import Input from '@material-ui/core/Input';
import InputLabel from '@material-ui/core/InputLabel';
import LockIcon from '@material-ui/icons/LockOutlined';
import Paper from '@material-ui/core/Paper';
import Typography from '@material-ui/core/Typography';
import withStyles from '@material-ui/core/styles/withStyles';
import { Field, reduxForm } from 'redux-form'
import TextField from '@material-ui/core/TextField'
import { IndefiniteObservable } from '../../../node_modules/indefinite-observable';
const styles = theme => ({
layout: {
width: 'auto',
display: 'block', // Fix IE11 issue.
marginLeft: theme.spacing.unit * 3,
marginRight: theme.spacing.unit * 3,
[theme.breakpoints.up(400 + theme.spacing.unit * 3 * 2)]: {
width: 400,
marginLeft: 'auto',
marginRight: 'auto',
},
},
paper: {
marginTop: theme.spacing.unit * 13,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
padding: `${theme.spacing.unit * 2}px ${theme.spacing.unit * 5}px ${theme.spacing.unit * 5}px`,
background: 'linear-gradient(to bottom, rgba(146, 135, 187, 0.8) 0%, rgba(0,0,0,0.6) 100%)',
transition: 'opacity 0.1s, transform 0.3s cubic-bezier(0.17, -0.65, 0.665, 1.25)',
transform: 'scale(1)'
// backgroundImage: `url("http://web3canvas.com/wp-content/uploads/2014/02/littlevisuals-high-quality-hd-banner-images-stock-photos-free-laptop-topview-download.jpg")`,
},
body: {
backgroundImage: `url("http://web3canvas.com/wp-content/uploads/2014/02/littlevisuals-high-quality-hd-banner-images-stock-photos-free-laptop-topview-download.jpg")`,
backgroundSize: 'cover',
},
color: {
color: 'black',
},
avatar: {
margin: theme.spacing.unit,
backgroundColor: theme.palette.secondary.main,
},
form: {
width: '100%', // Fix IE11 issue.
marginTop: theme.spacing.unit,
},
submit: {
marginTop: theme.spacing.unit * 2,
marginBottom: theme.spacing.unit * 2
},
});
const renderTextField = ({
input,
label,
meta: { touched, error },
...custom
}) => (
<TextField
hintText={label}
floatingLabelText={label}
errorText={touched && error}
{...input}
{...custom}
/>
)
const validate = values => {
const errors = {}
const requiredFields = [
'firstName',
'lastName',
'email',
'favoriteColor',
'notes'
]
requiredFields.forEach(field => {
if (!values[field]) {
errors[field] = 'Required'
}
})
if (
values.email &&
!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)
) {
errors.email = 'Invalid email address'
}
return errors
}
class LoginPage extends Component {
constructor(props) {
super(props);
// reset login status
this.props.dispatch(userActions.logout());
this.state = {
email: '',
password: '',
submitted: false
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleSocialLogin = this.handleSocialLogin.bind(this);
this.handleSocialLoginFailure = this.handleSocialLoginFailure.bind(this);
}
handleSocialLogin(user) {
console.log(user)
debugger;
if (user) {
this.props.dispatch(userActions.googlelogin(user));
}
}
handleSocialLoginFailure = (err) => {
console.error(err)
}
handleChange(e) {
const { name, value } = e.target;
this.setState({ [name]: value });
}
handleSubmit(e) {
debugger;
e.preventDefault();
this.setState({ submitted: true });
const { email, password } = this.state;
const { dispatch } = this.props;
if (email && password) {
dispatch(userActions.login(email, password));
}
}
render() {
const { classes } = this.props;
const { email, password, submitted } = this.state;
const { handleSubmit, pristine, reset, submitting } = this.props
return (
<div className={classes.body}>
<React.Fragment>
<CssBaseline />
<main className={classes.layout}>
<Paper className={classes.paper}>
<Avatar className={classes.avatar}>
<LockIcon />
</Avatar>
<Typography variant="headline" className={classes.color}>Sign in</Typography>
<form onSubmit={this.handleSubmit}>
<FormControl margin="normal" required fullWidth>
<Field
component={renderTextField}
label="Email"
id="email"
name="email"
value={email}
onChange={this.handleChange}
fullWidth
/>
</FormControl>
<FormControl margin="normal" required fullWidth>
<Field
value={password}
onChange={this.handleChange}
name="password"
type="password"
id="password"
component={renderTextField}
label="Password"
className={classes.color}
fullWidth />
</FormControl>
<Button type="submit"
disabled={pristine || submitting}
fullWidth
variant="outlined"
color="secondary"
className={classes.submit}
>
Submit
</Button>
</form>
<Button
fullWidth
variant="outlined"
color="primary"
className={classes.submit}>
<Link to="/register">
New User ? Register Here
</Link>
</Button>
<SocialButton
fullWidth
variant="raised"
color="primary"
className="btn btn-danger form-control"
provider='google'
appId='967209745915-djav2bq5ic5r4ad9on3itp5a079s1ruu.apps.googleusercontent.com'
onLoginSuccess={this.handleSocialLogin}
onLoginFailure={this.handleSocialLoginFailure}
key={'google'}
>
Login with Google
</SocialButton>
</Paper>
</main>
</React.Fragment>
</div>
);
}
}
LoginPage.propTypes = {
classes: PropTypes.object.isRequired,
};
function mapStateToProps(state) {
const { loggingIn } = state.authentication;
return {
loggingIn
};
}
export default compose(
withStyles(styles),
connect(mapStateToProps, null),
reduxForm({
form: 'MaterialUIForm',
validate
})
)(LoginPage);
我将在几分钟后将代码放到 stackblitz 上
解决方案
为每个组件创建唯一classNames
的,将其他内容包装在classNames
div 元素中。
登录组件
render() {
return (
<div className="login">
//other code
</div>
)
}
对于 Home 组件
render() {
return (
<div className="home">
//other code
</div>
)
}
在 index.css 中应用颜色classNames
。
.login {
background: url("http://web3canvas.com/wp-content/uploads/2014/02/littlevisuals-high-quality-hd-banner-images-stock-photos-free-laptop-topview-download.jpg") no-repeat;
background-size: cover;
min-width: 100%;
min-height: 100%;
}
.home {
background: url("https://www.w3schools.com/cssref/mountain.jpg") no-repeat; background-size: cover;
min-width: 100%;
min-height: 100%;
}
推荐阅读
- android - 在 Kotlin 中使用 contains() 的搜索系统以及与字符串和列表的结果差异
- python - 在 Python (pandas) 中填写缺失的日期和时间
- mocha.js - before(..) 块中的 cy.visit() 导致 CypressError:无法在正在运行的测试之外调用 cy.visit()
- python - PyCharm 处理本地包的方式不同吗?
- java - 在 Java 中运行线程时更改线程优先级的条件是什么?
- android - 后台服务无通知
- python - CERBOT ContextualVersionConflict: (zope.interface 4.3.2 (/usr/lib/python3/dist-packages)
- dart - 如何在飞镖中值部分的地图数据结构中分配变量?
- forms - 按钮打开表格
- python - 我尝试使用带有 OpenAI gym Environment 的 pytorch 实现 DQN。但是我的episode_rewardis减少了。为什么?