在React JS中为不同页面应用不同的背景图像

时间:2018-09-12 05:52:55

标签: css reactjs background-image

我希望登录页面和主页具有不同的背景图像。如果我将图像应用于body标签,则它将应用于所有页面。而且,当我将其应用于特定的登录页面时,它可以工作,但是只能根据登录页面的宽度和高度来应用它。

应用于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;
}

这是登录页面

enter image description here

这是主页

enter image description here

我只想在登录页面中显示背景图片。

当我仅将背景图片应用于登录页面时,就会发生这种情况。 enter image description here

我已在登录页面的最外面的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>

帮我一个人。

编辑-

我正在使用Material 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中

3 个答案:

答案 0 :(得分:0)

为每个组件创建唯一的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%;
}

答案 1 :(得分:0)

如果您要使用与Material UI完全兼容的样式化组件, 您只需将<div className={classes.body}>替换为自定义<StyledBody>

import styled from 'styled-components';

const StyledBody = styled.div`
  background: 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;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
`;

export default function Login(props) {
  return (
    <StyledBody>
      // your login component
    </StyledBody>
  );
}

如果尚未安装,请确保首先使用npm i styled-components

安装样式化组件。

当然,相同的CSS代码也可以使用,但是您想使用它。

答案 2 :(得分:0)

document.body.style.backgroundImage = "url('image url')";