一、基本配置
1.在react中一個css文件引入會導致全局都可以享用,爲了避免這種情況採用第三方組件'styled-components'
注意<GlobalStyle/>是一個單閉合的標籤,不然會出現不顯示的問題
全局使用:
//這裏的話是全局生效的
import { createGlobalStyle } from 'styled-components';
export const GlobalStyle = createGlobalStyle`
//xxx
`
//其他組件的引入,只要有一個組件引入就所有組件均生效
import {GlobalStyle} from "./style";
import Header from './common/header';
class App extends Component {
render(){
return (
<div >
<GlobalStyle/>
<Header></Header>
</div>
)
}
}
export default App;
局部組件使用:
//統一組件文件下的css樣式文件style.js
import styled from "styled-components";
export const HeaderWrapper = styled.div`
height:30px;
background:red;
`;
//帶屬性的
export const NavSearch = styled.input.attrs({
placeholder: '搜索'
})`
width: 160px;
`
//組件
mport React ,{Component} from 'react';
import {HeaderWrapper} from './style'
class Header extends Component {
render(){
return (
<div>
<HeaderWrapper>
header
</HeaderWrapper>
</div>
)
}
}
export default Header;
2.如果做pc端的項目,爲了保持所有瀏覽器下都一致,可以搜索reset.css複製樣式
二、reducer的拆分combineReducers
//總的reducer
import { combineReducers } from 'redux';
import headerReducer from '../common/header/store/reducer';
export default combineReducers({
header : headerReducer
})
//在devtools中會發現數據的上級是header,所以在組件中應該這樣獲取數據
const mapStateToProps = (state) => {
return {
focused: state.header.focused
};
};
三、關於immutable的使用(防止直接修改state中的數據
1.在github中進行搜索,immutable的英文是不可修改的,將js對象變爲一個immutable對象
官網https://immutable-js.github.io/immutable-js
2.其實state.set並不是直接修改state中的值,他其實是對比舊的state值,結合新的值生成一個新的immutable對象
//在reducer.js文件中
import { fromJS } from 'immutable';
//immutable將js對象變成了一個immutable對象
const defaultState = fromJS({
focused : false
});
export default (state=defaultState,action) => {
if(action.type === constants.SEARCH_FOCUS){
return state.set('focused',true);
}
if(action.type === constants.SEARCH_BLUR){
return state.set('focused',false);
}
return state;
}
//在組件中
const mapStateToProps = (state) => {
return {
focused: state.header.get('focused')
};
};
3.redux-immutable
安裝使用
//將原本的state的js對象變成了immutable對象,總的reducer文件
import { combineReducers } from 'redux-immutable';
import headerReducer from '../common/header/store/reducer';
export default combineReducers({
header : headerReducer
});
//組件文件中
const mapStateToProps = (state) => {
return {
// 第一版本
// focused: state.header.get('focused')
//第二版本:用了redux-immutable將state變成了一個immutable對象
//focused:state.get('header').get('focused')
//第三版:用redux-immutable中提供的api
focused:state.getIn(['header','focused'])
};
};
四、關於路由
1.安裝 react-router-dom =>
引入{Route , BrowserRouter} =>
在app.js中寫標籤<Route path='/detail/:id' exact component={Detail}></Route> =>
<Link key={index} to={'/detail/' + item.get('id')}> =>
每一次在Detail這個組件的渲染函數中傳入對應的id值,id值的獲取在this.props中存儲,打開控制檯看就可以了
二、注意點:
1.關於css中圖片的引入(特殊,因爲打包會吧../../看成是字符串
import logoPic from '../../statics/logo.png';
background: url(${logoPic});
2.報錯Cannot read property 'bind' of undefined
在底下寫一下這個函數就可以了,不要寫一半就着急查看是否報錯
3.要管理數據時redux和react-redux要一起安裝,react-redux是爲了我們方便的使用redux