1、項目基本搭建
create-react-app是react中最簡單的創(chuàng)建單頁面程序的方式。在使用它之前先保證你的機器上安裝了Node環(huán)境
# 全局安裝create-react-app
$ yarn global add create-react-app
# 創(chuàng)建項目
create-react-app react01
cd react01
yarn start
//瀏覽器localhost:3000/可以查看到開啟的服務(wù)
2、JSX語法簡介
簡單的JSX語法
const element = <h1>Hello, world!</h1>;
它被稱為 JSX, 一種 JavaScript 的語法擴展
在 JSX 中使用表達式
你可以任意地在 JSX 當中使用JavaScript 表達式在 JSX 當中的表達式要包含在大括號里
const str = "hello world" + "你好世界";
const element = (
<h1>
Hello, {str}
</h1>
);
JSX 本身其實也是一種表達式
在編譯之后呢,JSX 其實會被轉(zhuǎn)化為普通的 JavaScript 對象。
這也就意味著,你其實可以在 if 或者 for 語句里使用 JSX,將它賦值給變量,當作參數(shù)傳入,作為返回值都可以
const renderJsx = () => {
let a = 10;
if(a > 5){
return <div>hello {a}</div>
}else{
return <div>hello world</div>
}
}
//=======調(diào)用renderJsx()即可
render(){
return(
<div>{renderJsx()}</div>
)
}
JSX 屬性
//你可以使用引號來定義以字符串為值的屬性
const element = <div tabIndex="0"></div>;
//===
//也可以使用大括號來定義以 JavaScript 表達式為值的屬性
const element = <img src={user.avatarUrl} />;
切記你使用了大括號包裹的 JavaScript 表達式時就不要再到外面套引號了。JSX 會將引號當中的內(nèi)容識別為字符串而不是表達式
JSX 嵌套(可以相互嵌套)
const element = (
<div>
<h1>Hello!</h1>
<h2>Good to see you here.</h2>
</div>
);
因為 JSX 的特性更接近 JavaScript 而不是 HTML , 所以 React DOM 使用 camelCase 小駝峰命名 來定義屬性的名稱,而不是使用 HTML 的屬性名稱。
例如,class 變成了 className,而 tabindex 則對應(yīng)著 tabIndex
JSX 防注入攻擊
你可以放心地在 JSX 當中使用用戶輸入:
React DOM 在渲染之前默認會 [過濾]所有傳入的值。它可以確保你的應(yīng)用不會被注入攻擊。所有的內(nèi)容在渲染之前都被轉(zhuǎn)換成了字符串。這樣可以有效地防止 [XSS(跨站腳本)]攻擊。
const title = response.potentiallyMaliciousInput;
// 直接使用是安全的:
const element = <h1>{title}</h1>;
更多代碼注入注意:https://zhuanlan.zhihu.com/p/28434174
3、組件&props
1、組件定義
js函數(shù)定義
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
2、你也可以使用ES6 class來定義一個組件:
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
//調(diào)用
<Welcome name="lily"/>
3、組件渲染
import React, { Component } from 'react';
import './App.css';
//====組件 Welcome
function Welcome(props) {
return <div>hello, {props.name}</div>
}
const element = <Welcome name={"lily"}/>;
class App extends Component {
render() {
return (
<div className="App">
{element}
</div>
);
}
}
export default App;
4、生命周期詳解
1、state:傳遞及狀態(tài)的改變
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
//通過事件值的改變
clickEvent(){
this.setState({
date: "2019-03-27"
})
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
2、生命周期
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
componentDidMount() {
//當 `Clock` 組件第一次被渲染到 DOM 中的時候,就為其設(shè)置一個計時器這在 React 中被稱為“掛載(mount)”。
//=====設(shè)置計時器:
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
//同時,當 DOM 中 `Clock` 組件被刪除的時候,應(yīng)該清除計時器這在 React 中被稱為“卸載(umount)”。
//==清除計時器
clearInterval(this.timerID);
}
//定時器方法
tick() {
this.setState({
date: new Date()
});
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
3、正確地使用 State
不要直接修改 State,此代碼不會重新渲染組件
// Wrong
this.state.comment = 'Hello';
//yes
//而是應(yīng)該使用 setState():
this.setState({comment: 'Hello'});
4、State 的更新可能是異步的
出于性能考慮,React 可能會把多個 setState() 調(diào)用合并成一個調(diào)用。因為 this.props 和 this.state 可能會異步更新,所以你不要依賴他們的值來更新下一個狀態(tài)。
此代碼可能會無法更新計數(shù)器:
// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
});
要解決這個問題,可以讓 setState() 接收一個函數(shù)而不是一個對象。這個函數(shù)用上一個 state 作為第一個參數(shù),將此次更新被應(yīng)用時的 props 做為第二個參數(shù)
// Correct
this.setState((state, props) => ({
counter: state.counter + props.increment
}));
5、事件處理
1、事件命名:小駝峰式(camelCase)
6、條件渲染
與運算符 &&
function Mailbox(props) {
const unreadMessages = props.unreadMessages;
return (
<div>
<h1>Hello!</h1>
{unreadMessages.length > 0 &&
<h2>
You have {unreadMessages.length} unread messages.
</h2>
}
</div>
);
}
const messages = ['React', 'Re: React', 'Re:Re: React'];
ReactDOM.render(
<Mailbox unreadMessages={messages} />,
document.getElementById('root')
);
三目運算符
render() {
const isLoggedIn = this.state.isLoggedIn;
return (
<div>
The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in.
</div>
);
}
阻止組件渲染
在極少數(shù)情況下,你可能希望能隱藏組件,即使它已經(jīng)被其他組件渲染。若要完成此操作,你可以讓 render 方法直接返回 null,而不進行任何渲染
import React, { Component } from 'react';
function WarningBanner(props) {
if (!props.warn) {
return null;
}
return (
<div className="warning">
Warning!
</div>
);
}
class App extends Component {
render() {
return (
<div className="App">
<WarningBanner/>
</div>
);
}
}
export default App;
在組件的 render 方法中返回 null 并不會影響組件的生命周期。例如,上面這個示例中,componentDidUpdate 依然會被調(diào)用
7、列表keys
Keys 幫助 React 識別哪些元素改變了,比如被添加或刪除。因此你應(yīng)當給數(shù)組中的每一個元素賦予一個確定的標識
一個元素的 key 最好是這個元素在列表中擁有的一個獨一無二的字符串
當元素沒有確定 id 的時候,萬不得已你可以使用元素索引 index 作為 key
const todoItems = todos.map((todo, index) =>
// Only do this if items have no stable IDs
<li key={index}>
{todo.text}
</li>
);
8、狀態(tài)提升
通常,多個組件需要反映相同的變化數(shù)據(jù),這時我們建議將共享狀態(tài)提升到最近的共同父組件中去, 通過改變父級的狀態(tài)統(tǒng)一改變子組件的狀態(tài)