學(xué)習(xí)RN之前看這一篇React入門就夠了

000

React是一個(gè)用于構(gòu)建用戶界面的 JavaScript 庫,起源于Facebook內(nèi)部項(xiàng)目,13年已經(jīng)開源https://github.com/facebook/react。學(xué)習(xí)ReactNative首先要了解React相關(guān)的知識(shí)(當(dāng)然可以和RN同步學(xué)習(xí)),今天只是一個(gè)入門介紹但用于開發(fā)ReactNative已經(jīng)足夠了。

一、React優(yōu)勢

  • 虛擬DOM,HTML寫在JS里
  • 一切皆組件,支持自定義
  • 單向數(shù)據(jù)流,數(shù)據(jù)改變自動(dòng)同步視圖
  • Write once, run everywhere

二、HelloWorld

廢話不多說,先來個(gè)HelloWorld。

<html>
  <head>
    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> 
    <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
  </head>
  <body>
    <div id="example"></div>
    <script type="text/babel">
      ReactDOM.render(
        <h2>Hello World</h2>,
        document.getElementById('example')
      );
    </script>
  </body>
</html>

瀏覽器中打開查看效果,看到Hello World,恭喜你已經(jīng)入門了。

三、JSX

JSX語法簡單說就是HTML寫在JS里。想詳細(xì)了解的可以查看官方文檔https://reactjs.org/docs/introducing-jsx.html

四、組件Component

創(chuàng)建組件一共有3中方式,建議選擇第一和第三種。

  • 組件中只能有一個(gè)根節(jié)點(diǎn)
  • 組件首字母必須大寫,否則會(huì)被解析成html標(biāo)簽
  • 組件類對應(yīng)的標(biāo)簽的用法和HTML標(biāo)簽的用法完全一致,可以加入任意的屬性
  • 具有可組合、可重用、可維護(hù)的特征

無狀態(tài)函數(shù)式組件

無狀態(tài)函數(shù)式組件形式上表現(xiàn)為一個(gè)只帶有一個(gè)render方法的組件類,通過函數(shù)形式或者箭頭函數(shù),并且該組件是無state狀態(tài)的。

var HelloA = (props) => {
    return <h2>{props.name}</h2>
}

React.createClass

React.createClass是react剛開始推薦的創(chuàng)建組件的方式,這是ES5的原生的JavaScript來實(shí)現(xiàn)的React組件。

var HelloMessage = React.createClass({
    render: function() {
        return (<h1>Hello</h1>);
    }
});

class

React.Component是以ES6的形式來創(chuàng)建react的組件的,是React目前極為推薦的創(chuàng)建有狀態(tài)組件的方式,最終會(huì)取代React.createClass形式。

class HelloM extends React.Component{
    render(){
        return <h1>Hello {this.props.name}</h1>;
    }
};

五、組件生命周期

先來個(gè)標(biāo)準(zhǔn)的ES6組件生命周期代碼

class LifeComponent extends React.Component{
    constructor(props){
        super(props)
        console.log('構(gòu)造函數(shù)')
        this.state={
            title:props.title
        }
    }
    componentWillMount(){
        console.log('componentWillMount');
    }
    componentDidMount(){
        console.log('componentDidMount');
    }
    shouldComponentUpdate(){
        console.log('shouldComponentUpdate');
        return true;
        }
    componentWillUpdate(){
        console.log('componentWillUpdate');
    }

    componentDidUpdate(){
        console.log('componentDidUpdate');
    }
    componnentWillReceiveProps(){
        console.log('componnentWillReceiveProps');
    }
    render(){
        console.log('render');
        return(
            <div>
                <h1>{this.state.title}</h1>
            </div>
        );
    } 
 }
LifeComponent.propTypes = {
    title:React.PropTypes.string,
}
LifeComponent.defaultProps = {
    title:'標(biāo)題',
}
ReactDOM.render(
    <LifeComponent/>,
    document.getElementById('example')
);

組件的生命周期介紹圖如下:

圖片來自http://blog.guowenfh.com/2017/02/05/2017/es6-react-life-cycle/

注意:

componentWillMount() 、componentDidMount() 、componentWillReceiveProps() 這三個(gè)函數(shù)中允許調(diào)用setState,

shouldComponentUpdate、 componentWillUnmount 調(diào)用setStat無效

componentWillUpdate、componentDidUpdate 調(diào)用setStat會(huì)死循環(huán)

?

六、Props 、 State對比

相同

  • 都是用于描述組件狀態(tài)的
  • 都可以改變,改變都會(huì)觸發(fā)組建的重新渲染

不同

  • Props是由外部傳入的,是父組件傳遞給子組件的數(shù)據(jù)流。
  • State是內(nèi)部定義的,代表組件的內(nèi)部狀態(tài)。在內(nèi)部改變與外部組件沒有直接聯(lián)系。
  • Props通常在組件外部發(fā)生變化,在內(nèi)部保持不變。
  • 一個(gè)組件不能改變自身的props, 但要負(fù)責(zé)設(shè)置子組件的 props。

七、箭頭函數(shù)

ES6之前按鈕點(diǎn)擊我們可能是這樣寫的:

class LButton extends React.Component{
        render(){
          return <button onClick={this.handleClick.bind(this)} style={this.state}>{this.props.name}</button>;
        }
        handleClick(){
            this.setState({fontSize:30,color:'white', backgroundColor:'red'});
        }
 };

需要在調(diào)用handleClick的地方綁定this。ES6之后使用箭頭函數(shù)就不用了,請看實(shí)例:

class LLButton extends React.Component{
    render(){
      return <button onClick={()=>{
            this.setState({fontSize:30,color:'white', backgroundColor:'blue'});
      }} style={this.state}>{this.props.name}</button>;
    }
};

或者

class LLLButton extends React.Component{
    render(){
      return <button onClick={()=> this.handleClick()} style={this.state}>{this.props.name}</button>;
    }
    handleClick(){
        this.setState({fontSize:30,color:'white', backgroundColor:'yellow'});
    }
};

更多箭頭函數(shù)介紹請?jiān)L問:https://reactjs.org/docs/faq-functions.html#is-it-ok-to-use-arrow-functions-in-render-methods

八、獲取真實(shí)的DOM節(jié)點(diǎn)

React提供了一個(gè)獲取組件的的方式: Refs。

使用場景:

  • 處理焦點(diǎn)、文本選擇或媒體控制。
  • 觸發(fā)強(qiáng)制動(dòng)畫。
  • 集成第三方 DOM 庫

如果可以通過聲明式實(shí)現(xiàn),則盡量避免使用 refs。即能用State或者Props實(shí)現(xiàn)的不要用Refs。

來個(gè)例子直觀了解一下Refs:

<!DOCTYPE html>
<html>
  <head>
    <script src="https://cdn.bootcss.com/react/15.4.2/react.min.js"></script>
    <script src="https://cdn.bootcss.com/react/15.4.2/react-dom.min.js"></script>
    <script src="https://cdn.bootcss.com/babel-standalone/6.22.1/babel.min.js"></script>
    
  </head>
  <body>
    <div id="example"></div>
    <script type="text/babel">
      class RefComponent extends React.Component{
        render(){
          return (
            <div>
                <input type="text" ref="lTextInput" />
                <input type="button" value="Focus the text input" onClick={this.handleClick.bind(this)} />
            </div>
          );
        }
        handleClick(){
            this.refs.lTextInput.focus();
        }
      };

      ReactDOM.render(
        <RefComponent />,
        document.getElementById('example')
      );
    </script>
  </body>
</html>

九、表單提交

下面看一個(gè)官網(wǎng)的表單提交的例子。輸入框中的值變化時(shí)通過onChange保存到State中,點(diǎn)擊提交時(shí)從State中取出提交。

class NameForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {value: ''};       
    }
    render() {
        return (
            <form onSubmit={(event)=> {
                alert('A name was submitted: ' + this.state.value);
                event.preventDefault();
            }}>
            <label>
                Name:
                <input type="text" value={this.state.value} onChange={(event)=> {
                    this.setState({value: event.target.value});
                }}/>
            </label>
            <input type="submit" value="Submit" />
            </form>
        );
    }
}
ReactDOM.render(
    <NameForm />,
    document.getElementById('example')
);

運(yùn)行效果:

運(yùn)行效果

十、何去何從

學(xué)習(xí)ReactNative掌握這些React知識(shí)基本可以開始搞了,如果你想更深入的學(xué)習(xí)React可以到React中文網(wǎng)站查看文檔和教程https://doc.react-china.org/

更多iOS、逆向、ReactNative開發(fā)文章請專注微信公眾號(hào):樂Coding

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容