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