天行健, 君子以自强不息
Sunny's Blog
Title

React Quick Start 2018

react-devtools官方推荐调试工具github地址

这篇主要讨论一下react v16.3.2版本下的一下基本编码注意事项(Quick Start),主要涉及jsx,elements,components,props,state,event,Conditional Rendering,keys,form(controlled and uncontrolled), state lift up and composition。其中keys,form我会单独拿出一个blog来详细讲,state lift up是一个state设计理念,我之前的blog有分析过,剩下的内容我都会在这篇blog中进行记录。主要是根据官方文档和自己coding中遇到的问题进行的总结。

1.jsx

1).React用component的概念将markup和logic放在一个文件,这个文件的类型推荐jsx。

2).Jsx是js的语法扩展,里面包含了js和html两种编码风格。任何的js表达式(不包含if,for等语句)都可以在{}中嵌入jsx语法。

3).jsx本身也是一个js表达式,所以jsx可以嵌入在if,for的js语句中

                    function getGreeting(user) {
                      if (user) {
                        return <h1>Hello, {formatName(user)}!</h1>;
                      }
                      return <h1>Hello, Stranger.</h1>;
                    }
            

4).在同一个属性中,比如className,要么用className={},要么用className="xxx",不能className="{}",但是可以className={''}

5).Jsx中的tag一定要有/>

6).jsx可以防御注入攻击

                 const title = response.potentiallyMaliciousInput;
                 // This is safe:
                 const element = <h1>{title}</h1>;
            

2.elements

1).Elements are the smallest building blocks of React apps. element是组成component的基本单位,就类似一个tag

                const element = <h1>Hello, world</h1>;
            

3.components

1).Components let you split the UI into independent, reusable pieces, and think about each piece in isolation. 我的感觉react single component是划分页面UI的基本单位,要尽量保持“只做一件事”的原则。

2).Components类似于js中的function,他们接收参数(props),return一段React elements出来

3).目前比较流行的是ES6的class来定义components,但是原则上function也可以定义

                    //以下两种是一致的
                    function Welcome(props) {
                      return <h1>Hello, {props.name}</h1>;
                    }

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

4).A good rule of thumb is that if a part of your UI is used several times (Button, Panel, Avatar), or is complex enough on its own (App, FeedStory, Comment), it is a good candidate to be a reusable component.我的感觉是只要项目前期规划是react框架,就应该尽量将组件react化。

4.props

1).Props are Read-Only. All React components must act like pure functions with respect to their props.(components是不可以修改props的)

5.state

1).There are three things you should know about setState().

                    1)Do Not Modify State Directly
                    // Wrong
                    this.state.comment = 'Hello';
                    // Correct
                    this.setState({comment: 'Hello'});
                    //the only place where you can assign this.state is the constructor.

                    2)State Updates May Be Asynchronous(不要直接用{isToggleOn: this.state.isToggleOn})
                    this.setState(prevState => ({
                      isToggleOn: !prevState.isToggleOn
                    }));

                    3)State Updates are Merged (setState谁就updated谁,其他的state属性保持不变)
                    //The merging is shallow, so this.setState({comments}) leaves this.state.posts intact, but completely replaces this.state.comments.
            

2).parent的state可以作为props传给子组件

6.event

1).Handling events with React elements is very similar to handling events on DOM elements. There are some syntactic differences

                    1).React events are named using camelCase, rather than lowercase.
                    2).With JSX you pass a function as the event handler, rather than a string.
                        //Html 
                        <button onclick="activateLasers()">
                            Activate Lasers
                        </button>
                        //React 注意1),2)两条
                        <button onClick={activateLasers}>
                            Activate Lasers
                        </button>
                    3)Another difference is that you cannot return false to prevent default behavior in React. 
                        //You must call preventDefault explicitly.(return false不能阻止默认事件在react中,但是在一般js中是可以的)
            

2).Passing Arguments to Event Handlers

                //testHandler中参数,第一个是data,第二个才是event
                testHandler(data, e){
                    e.preventDefault();
                    console.log(e);
                    console.log('============');
                    console.log(data); //7
                    this.setState(prevState => ({
                        flag: !prevState.flag
                    }));
                }
                ...
                return...
                <button onClick={this.testHandler.bind(this, 7)}>button</button>
            

7.Conditional Rendering

1).Inline If with Logical && Operator.It works because in JavaScript, true && expression always evaluates to expression, and false && expression always evaluates to false. Therefore, if the condition is true, the element right after && will appear in the output. If it is false, React will ignore and skip it.

2).Inline If-Else with Conditional Operator. condition ? true : false.

3).Preventing Component from Rendering. In rare cases you might want a component to hide itself even though it was rendered by another component. To do this return null instead of its render output.

                { this.state.flag ? (<div >error</div >): null }
            

8.keys(另写blog)

9.form(另写blog)

10.state lift up.

1).见React组件编写步骤(从UI到jsx实现)

11.composition

Composition这块我觉得主要是讲了react构造组件的几个基本技巧。

1).构造未知组件占位方法, 利用props.children

                ...
                function Navigation(props){
                    return(
                        <ul className={'navigation ' + props.position}>
                            {props.children}
                        </ul>
                    )
                }
                function MultipleNavigation(props){
                    return(
                        <div>
                            <ul className='navigation-left'>
                                {props.left}
                            </ul>
                            <ul className='navigation-right'>
                                {props.right}
                            </ul>
                        </div>
                    )
                }
                ...
                return...
                    <Navigation position="left">
                        <li>left-item1</li>
                        <li>left-item2</li>
                        <li>left-item3</li>
                        <li>left-item4</li>
                    </Navigation>
                    <Navigation position="right">
                        <li>right-item1</li>
                        <li>right-item2</li>
                        <li>right-item3</li>
                        <li>right-item4</li>
                    </Navigation>
            

2).构造未知组件占位方法, 有时候你需要多个占位,那就需要充分利用props

            ...
                <MultipleNavigation left='' right='' />
            ...
            

3).构造一个通用组件的时候,尽量将非通用属性(包括test,function,class等等)都通过props来表示,要记住的是Remember that components may accept arbitrary props, including primitive values, React elements, or functions.

地势坤,君子以厚德载物