如何在ReactJS中的div中放置元素?

时间:2018-12-29 14:14:42

标签: html css reactjs

我是一个完整的初学者。我正在用React做一个简单的游戏。

为此,我正在制作这样的游戏板

enter image description here

如您所见,我在左侧将两个div堆叠在一起。我也想在右侧彼此叠放两个div。我该怎么办?

我的代码:

Board.js

class Board extends Component {



    render() {
        return (
            <div className="board">
                <Square placement={'topLeft'}/>
                <Square placement={'bottomLeft'}/>
            </div>
        )
    }
}

export default Board;

Board.css

.board{
    width: 500px;
    height: 500px;
    margin: 40px auto 0;
    border: 5px solid black;
    border-radius: 5px;
    background-color: darkgray;
}

@media(max-width: 650px) {
    .board {
        width: 300px;
        height: 300px;
        margin: 90px auto 0;
        border: 5px solid black;
        border-radius: 5px;
    }
}

Square.js

const Square = (props) => {

    let className;

    switch (props.placement) {
        case 'topLeft':
            className='square topLeft';
            break;
        case 'bottomLeft':
            className = 'square bottomLeft';
    }


    return (
        <div className={className}>
            <p style={{fontSize:'100px'}}></p>
        </div>
    );
};

export default Square;

Square.css

.square {
    width: 50%;
    height: 50%;
}

.topLeft{
    border-right: 5px solid black;
    border-bottom: 5px solid black;
}

.bottomLeft{
    border-top: none;
    border-right: 5px solid black;
}

1 个答案:

答案 0 :(得分:0)

您可以制作一个两列网格,并在左上角和右下角的正方形上赋予内部边框。

您的代码应如下所示:

Board.js

class Board extends React.Component {
  render() {
    return ( 
      <div className="board">
        <Square placement={'topLeft'}/>
        <Square placement={'topRight'}/>
        <Square placement={'bottomLeft'}/>  //added 2 more squares
        <Square placement={'bottomRight'}/>    
      </div>
    )
  }
}

Board.css

.board{
  width: 500px;
  height: 500px;
  margin: 40px auto 0;
  border: 5px solid black;
  border-radius: 5px;
  background-color: darkgray;
  display: grid;
  grid-template-columns: 1fr 1fr; //two equal size columns layout
}

@media(max-width: 650px) {
  .board {
    width: 300px;
    height: 300px;
    margin: 90px auto 0; //You don't need to add the border again inside the media query
  }
}

Squares.js

const Square = (props) => {
  let className;
  switch (props.placement) {
    case 'topLeft':
      className='square topLeft';
      break;
    case 'topRight':
      className='square'
      break;
    case 'bottomLeft':
      className='square';
      break;
    case 'bottomRight':
      className = 'square bottomRight';
  }
  return (
    <div className={className}>
      <p style={{fontSize:'100px'}}></p>
    </div>
  );
};

Squares.css

.square {
  width: 100%;
  height: 100%;
}

.topLeft{
  border-right: 5px solid black;
  border-bottom: 5px solid black;
}

.bottomRight{
  border-top: 5px solid black;
  border-left: 5px solid black;
}