react-组件状态练习-移动的小球球

直接贴代码

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import Ball from './components/Ball';


const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <Ball 
      xSpeed={100} ySpeed={130} bg='lightblue' 
    />
  </React.StrictMode>
);

Ball.css

.ball {
  position: fixed;
  width: 100px;
  height: 100px;
  border-radius: 50%;
}

Ball.js

import React, { Component } from 'react'
import './Ball.css'

/**
 * 一个满屏幕乱窜的小球
 * 横向速度 向右用正数表示 向左用负数  单位 像素/s
 * 纵向速度 向下用正数表示 向上用负数  单位 像素/s
 * porps : xSpeed ySpeed left top bg
 * state : xSpeed ySpeed left top
 */
export default class Ball extends Component {

  state = {
    xSpeed: this.props.xSpeed,
    ySpeed: this.props.ySpeed,
    left: this.props.left || 0,
    top: this.props.top || 0
  }

  componentDidMount() {
    const duration = 16 // 运行速度为一帧  16毫秒
    setInterval(()=> {
      const xDis = this.state.xSpeed * duration / 1000 // 横向每秒移动的距离
      const yDis = this.state.ySpeed * duration / 1000 // 纵向每秒移动的距离
      let nextLeft = this.state.left + xDis // 得到将要移动到的横向位置
      let nextTop = this.state.top + yDis // 得到将要移动到的纵向位置

      if (nextLeft <= 0) { // 如果超出屏幕左边界
        nextLeft = 0
        this.setState({
          xSpeed: -this.state.xSpeed // 重新设置横向速度
        })
      }else if (nextLeft >= document.documentElement.clientWidth - 100) { // 超出屏幕右边界,100为小球宽度
        nextLeft = document.documentElement.clientWidth - 100
        this.setState({
          xSpeed: -this.state.xSpeed // 重新设置横向速度
        })
      }

      if (nextTop <= 0) { // 如果超出屏幕上边界
        nextTop = 0
        this.setState({
          ySpeed: -this.state.ySpeed // 重新设置纵向速度
        })
      }else if (nextTop >= document.documentElement.clientHeight - 100) { // 超出屏幕下边界,100为小球高度
        nextTop = document.documentElement.clientHeight - 100
        this.setState({
          ySpeed: -this.state.ySpeed // 重新设置纵向速度
        })
      }

      // 最后统一设置小球位置
      this.setState({
        left: nextLeft,
        top: nextTop
      })
    }, duration)
  }

  render() {
    return (
      <div className='ball' style={{
        left: this.state.left,
        top: this.state.top,
        backgroundColor: this.props.bg || '#F40'
      }}></div>
    )
  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

合法的咸鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值