【问题标题】:Reactjs: Is there a way to center a picture?Reactjs:有没有办法让图片居中?
【发布时间】:2023-04-10 22:55:01
【问题描述】:

我已经写了你可以在这里看到的网站:https://konekto-1var7fhic.now.sh

我目前很担心这个屏幕:screenshot-landingpage

我想使图标居中,已经尝试了很多,但仍然无法正常工作,因为我不知道如何对其应用样式。在这里你可以看到我的代码:

import React from 'react';
import { Button, Grid } from '@material-ui/core';
import { withStyles } from '@material-ui/core/styles';
import AppContext from '../utils/AppContext';
import { Header } from '../Layout';
import SOSButton from './SOSButton';
import axios from 'axios';
import CONST from '../utils/Constants';
import AmbulanceIcon from '../utils/icons/Ambulance-small.png';
const styles = theme => ({
  container: {
    justifyContent: 'center',
    alignItems: 'center',
    // background: 'white',
    border: 'black',
    'border-width': 'medium',
    'margin-top': '80px',
    background: 'rgba(255, 255, 255, 0.8)',
    'border-radius': '20px'
  },
  item: {
    // background: 'red',
    width: '100%',
    //background: 'white',
    'text-align': 'center',
    'border-radius': '5px',
    'margin-top': '10px'
  },
  icon: {
    height: '50px',
    width: '50px'
  }
});

class Landingpage extends React.Component {
  static contextType = AppContext;

  constructor(props) {
    super(props);
    this.classes = props.classes;
    this.state = {};
    this.handleDirectSOS = this.handleDirectSOS.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
  }

  componentDidMount() {
    console.log(this.context);

    if (this.context.onBoardingStatus === false) {
      console.log('IN IF');
      this.props.history.push('/onboarding');
    }
  }
  handleDirectSOS() {
    console.log('direct SOS');
    this.props.history.push('/emergency_sent');
  }

  onSubmit(e) {
    console.log('in OnSubmit');
    axios
      .post(CONST.URL + 'emergency/create', {
        id: 1,
        data: this.state
      })
      .then(res => {
        console.log(res);
        console.log(res.data);
      })
      .catch(err => {
        console.log(err);
      });
  }

  render() {
    return (
      <React.Fragment>
        <Header title="Send out SOS" />
        <Grid
          container
          className={this.classes.container}
          direction="column"
          spacing={2}
        >
          <Grid
            item
            sm={12}
            className={(this.classes.item, this.classes.forwardbutton)}
          >
            <div className={this.classes.imageContainer}>
            <img src={AmbulanceIcon} alt="AmbulanceIcon" />{' '}
            </div>
            <SOSButton onSubmit={this.onSubmit} />
          </Grid>
        </Grid>
      </React.Fragment>
    );
  }
}

export default withStyles(styles)(Landingpage);

感谢您的帮助!

编辑:图片现在居中,但在按下“立即获取帮助”后不再居中。

我不明白这一点,因为按钮的更改仅在不包含或操作徽标的 SOS 按钮文件中进行管理:

import React from 'react';
import { withRouter } from 'react-router-dom';
import Button from '@material-ui/core/Button';
import { withStyles } from '@material-ui/core/styles';

const styles = theme => ({
  sosbutton: {
    background: '#e45050',
    'text-align': 'center',
    'margin-top': '30px',
    height: '80%',
    width: '100%'
  }
});
class SOSButton extends React.Component {
  constructor(props) {
    super(props);
    this.classes = props.classes;
    this.state = {
      timerOn: false
    };
    this.timerStart = this.timerStart.bind(this);
    this.timerStop = this.timerStop.bind(this);
    this.tick = this.tick.bind(this);
    this.counter = 3;
    this.counterStep = 1;
  }

  timerStart() {
    this.timerID = setInterval(() => this.tick(), 1000);
    this.setState({ timerOn: true });
  }

  timerStop() {
    clearInterval(this.timerID);
    this.counter = 3;
    this.setState({ timerOn: false });
    this.props.history.push('/');
  }

  tick() {
    this.counter = this.counter - this.counterStep;
    if (this.counter <= 0) {
      this.setState({ timerOn: false });
      this.timerStop();
      this.props.onSubmit();
      this.props.history.push('/emergency_sent');
    } else {
      this.setState({ timerOn: true });
    }
    console.log(this.counter);
  }

  render() {
    let timerOn = this.state.timerOn;
    let button;

    if (timerOn) {
      button = (
        <div>
          You have {this.counter} seconds to cancel the emergency SOS. <br />
          <br />
          <Button size="large" color="primary" onClick={this.timerStop}>
            Press here to cancel emergency call!
          </Button>
        </div>
      );
    } else {
      button = (
        <Button className={this.classes.sosbutton} onClick={this.timerStart}>
          GET HELP NOW!
        </Button>
      );
    }

    console.log(button);
    return button;
  }
}

export default withRouter(withStyles(styles)(SOSButton));

在此处查看新网站:https://konekto-58wgrs51r.now.sh

【问题讨论】:

  • 我想你可能忘记了 display: flex

标签: css reactjs image styling


【解决方案1】:

您需要将img 标签包装在它自己的div 中,并相应地设置div 的样式。在这种情况下,我给了div 一个imageContainer 的类。见下文:

import React from 'react';
import { Button, Grid } from '@material-ui/core';
import { withStyles } from '@material-ui/core/styles';
import AppContext from '../utils/AppContext';
import { Header } from '../Layout';
import SOSButton from './SOSButton';
import axios from 'axios';
import CONST from '../utils/Constants';
import AmbulanceIcon from '../utils/icons/Ambulance-small.png';
const styles = theme => ({
  container: {
    justifyContent: 'center',
    alignItems: 'center',
    // background: 'white',
    border: 'black',
    'border-width': 'medium',
    'margin-top': '80px',
    background: 'rgba(255, 255, 255, 0.8)',
    'border-radius': '20px'
  },
  item: {
    // background: 'red',
    width: '100%',
    //background: 'white',
    'textAlign': 'center',
    'borderRadius': '5px',
    'marginTop': '10px'
  },
  icon: {
    height: '50px',
    width: '50px'
  },
  imageContainer: {
    display: 'flex';
    justifyContent: 'center'
    width: '250px'
  }
});

class Landingpage extends React.Component {
  static contextType = AppContext;

  constructor(props) {
    super(props);
    this.classes = props.classes;
    this.state = {};
    this.handleDirectSOS = this.handleDirectSOS.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
  }

  componentDidMount() {
    console.log(this.context);

    if (this.context.onBoardingStatus === false) {
      console.log('IN IF');
      this.props.history.push('/onboarding');
    }
  }
  handleDirectSOS() {
    console.log('direct SOS');
    this.props.history.push('/emergency_sent');
  }

  onSubmit(e) {
    console.log('in OnSubmit');
    axios
      .post(CONST.URL + 'emergency/create', {
        id: 1,
        data: this.state
      })
      .then(res => {
        console.log(res);
        console.log(res.data);
      })
      .catch(err => {
        console.log(err);
      });
  }

  render() {
    return (
      <React.Fragment>
        <Header title="Send out SOS" />
        <Grid
          container
          className={this.classes.container}
          direction="column"
          spacing={2}
        >
          <Grid
            item
            sm={12}
            className={(this.classes.item, this.classes.forwardbutton)}
          >
            <div className={this.classes.imageContainer}>
                <img src={AmbulanceIcon} alt="AmbulanceIcon" />{' '}
            </div>
            <SOSButton onSubmit={this.onSubmit} />
          </Grid>
        </Grid>
      </React.Fragment>
    );
  }
}

export default withStyles(styles)(Landingpage);

【讨论】:

  • 谢谢!请查看问题的编辑,如果您也可以帮助我解决该问题,那就太好了。
  • @pythonlearner 在 imageContainer 类中,删除width: 250px,它应该可以工作。
【解决方案2】:

您的第一个问题是您需要将样式更改为驼峰式。其次,您只需将 display flex 和 justify 内容添加到中心,它应该使您的图像居中

item: {
    // background: 'red',
    width: '100%',

    //background: 'white',
    textAlign: 'center',
    borderRadius': '5px',
    marginTop: '10px',
    display: "flex",
    justifyContent: "center
  },

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-02
    • 2021-02-20
    • 2020-04-01
    • 2022-08-16
    • 2011-05-15
    • 2014-01-30
    • 1970-01-01
    相关资源
    最近更新 更多