React静态文件、公共样式、公共方法

一、静态文件

1、App.js引入logo

react脚手架搭建好后,在App.js中引入了logo

import logo from './logo.svg';

使用

<img src={logo} className="App-logo" alt="logo" />

logo.svg图片存放在src目录下

2、public目录下

public目录不会被webpack打包。神奇的是,index.html文件也在此目录下,该文件里有个id为root的div,用来渲染src里的index.js。
在index.html里也有引入public下的图片,比如ico

<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />

我想组件中怎么用public下的静态文件

<img src={process.env.PUBLIC_URL + '/favicon.ico'} ></img>  

process.env?

二、公共样式

在src目录下新建assets文件夹,建立ant.css文件

h2{color: tomato;}

再在src/components/ant.js组件中引入

import React from 'react';
import '../assets/ant.css'

class ant extends React.Component{
      render(h) {
          return(
              <div>
                  <h2>满堂花醉三千客</h2>             
                  <img src={process.env.PUBLIC_URL + '/favicon.ico'} ></img>          
              </div>
          )
      }
}
export default ant

三、公共方法

Vue中的公共方法:https://blog.csdn.net/m0_56262444/article/details/117807607?spm=1001.2014.3001.5501
在assets文件夹下新建ant.js文件
系统时间:

export function settime() {
    return function(value) {
    var date = new Date(value);
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    month = month < 10 ? "0" + month : month;
    var day = date.getDate();
    day = day < 10 ? "0" + day : day;
    var hour = date.getHours();
    hour = hour < 10 ? "0" + hour : hour;
    var minute = date.getMinutes();
    minute = minute < 10 ? "0" + minute : minute;
    var second = date.getSeconds();
    second = second < 10 ? "0" + second : second;
    return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
    }
  }
const systime=settime()

export{
    systime
}

在Ant.js组件中引入

import React from 'react';
import '../assets/ant.css'
import {systime} from '../assets/ant'

class ant extends React.Component{
    constructor(){
        super()
        this.state={
            temp:''
        }
    }
      render(h) {
          return(
              <div>
                  <h2>满堂花醉三千客</h2>             
                  <img src={process.env.PUBLIC_URL + '/favicon.ico'} ></img>  
                  {this.state.temp}
              </div>
          )
      }
      componentDidMount(){
           this.timer=setInterval(() => {
              this.setState({temp:systime(new Date())})              
          }, 1000);
      }
      componentWillUnmount(){
          if (this.timer) {
              clearInterval(this.timer)
          }
      }
}

export default ant
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值