Home > Web Front-end > JS Tutorial > A collection of simple and practical knowledge points about React (with example code)

A collection of simple and practical knowledge points about React (with example code)

寻∝梦
Release: 2018-09-11 15:22:04
Original
1294 people have browsed it

This article mainly talks about a collection of some simple and practical knowledge about react. Now let’s take a look at the specific content of this article

1: React life cycle

1.1 Display of three states of component life cycle:
- Mounting: The real dom structure has been inserted
- Updating: Being re-rendered
- Unmounting: The real dom structure has been moved out

1.2 Processing function about the life cycle (will means called before entering the state, did means called after entering the state)

componentWillMount()//The component will be Render to the real dom node;

componentDidMount()//The component has been rendered to the real dom node;

componentWillUpdate()//The state value changes and the component will be re-rendered;

componentDidUpdate()//The component has completed re-rendering;

componentWillUnmout()//Unload the component, such as when jumping to the route

componentWillReceiveProps() //The component props have been loaded. Called when there is a change;

shouldComponentUpdate()//Called when the component determines whether to re-render;

1.3 The execution sequence of the component life cycle is as shown in the figure below:
A collection of simple and practical knowledge points about React (with example code)

2: Find dom node operation (ref)

1 In react, add a name to the dom node through ref, and then we get it through this.refs.ref name

eg:

render(){    return (
        <p ref = "demo">this is a test</p>
    )
}
Copy after login

As shown in the above code, when we need to obtain the p tag, we can perform a series of operations through this.refs.demo, just like in native javascript through document. The same thing is obtained by getElementById;

3: Controlled form component

1. The value in the controlled form component must be bound to the state attribute, and needs to be passed onChange method to change the value;
eg:

export default class Demo extends React.Component{
            constructor(props){                super(props)                this.state = {
                    testInput: &#39;&#39;
                }
            }
            handleInput = (e) => {
                let str = &#39;&#39;
                if(e.target.value.length >= 8){                    str = e.target.value.splice(0,5) + &#39;...&#39;
                }                this.setState({
                    testInput: str
                })
            }
            render(){                return (
                    <p>
                        <input type="text" value={ this.state.testInput } onChange={ this.handleInput }>
                    </p>
                )
            }
        }
Copy after login

Four: About attribute verification

static: propTypes = {
     userName: React.PropTypes.bool.isRequired, //表示是必填项且是布尔类型
     passWord: React.PropTypes.number //表示必须是数值类型
}
Copy after login

More methods about attribute verification...

Five: About props

The props in the component mainly implement the transmission of data from the parent component to the child component

As shown in the demo below

DemoTest.js

import React,{Component} from &#39;react&#39;import Test from &#39;./Test.js&#39;export default class Demo extends Component{
    constructor(props){        super(props)        this.state={
        }
    }
    render(){        return(
            <p>
                <Test wenzi="按钮"/>
                <p>内容</p>
            </p>
        )
    }
}
Copy after login

Test.js

import React,{Component} from &#39;react&#39;export default class Demo extends Component{
    constructor(props){        super(props)        this.state={
        }
    }
    render(){        return(
            <input type="button" value={ this.props.wenzi }/>
        )
    }
}
Copy after login

The Test component can receive the wenzi value passed in the DemoTest component (if you want to know more, go to the PHP Chinese website React Reference Manual column to learn)

A collection of simple and practical knowledge points about React (with example code)

6: Descendant level data attribute transfer (context)

Explanation: This effect can also be achieved if we use props, but in that case, it will undoubtedly be more troublesome. The code below is

import React,{Component} from &#39;react&#39;class Child extends Component{
    constructor(props){        super(props)        this.state={
        }
    }    static contextTypes = {
        wenzi: React.PropTypes.string
    }
    render(){        return(
            <p>
                <input type="button" value={ this.context.wenzi }/>
            </p>
        )
    }
}class Son extends Component{
    constructor(props){        super(props)        this.state={
        }
    }
   render(){        return(
            <p>
                <Child />
            </p>
        )
    }
}
export default class Parent extends Component{
    constructor(props){        super(props)        this.state={
        }
    }
    getChildContext = () => {        return{
            wenzi: &#39;测试按钮&#39;
        }
    }    static childContextTypes = {
        wenzi: React.PropTypes.string
    }
    render(){        return(
            <p>
                <Son />
            </p>
        )
    }
}
Copy after login

effect achieved through context: A collection of simple and practical knowledge points about React (with example code)

Seven: Add animation in react (react-addons-css-transition-group)

react-addons-css The -transition-group component only provides the animation function of displaying and hiding the content;

Basic usage:
1. Install->import
2. Which part do you want to have the display and hide animation? Just wrap it with this component

<ReactCSSTransitionGroup    transitionName="example"
    transitionAppear={true}
    transitionEnterTimeout={500}
    transitionLeaveTimeout={300}>{ items }</ReactCSSTransitionGroup>
Copy after login

Set some display and hidden css styles according to the specified transitionName value

.example-enter{ 
//此处填写的是进入的样式 eg: opacity: 0;
}.example-enter.example-enter-active{ 
//此处填写的是进入结束的样式 eg: opacity: 1;
    transition: opacity 500ms ease-in;
}.example-leave{ 
//此处填写的是离开的样式 eg: opacity: 1;
}.example-leave.example-leave-active{ 
//此处填写的是离开结束的样式 eg: opacity: 0;
    transition: opacity 500ms ease-in;
}//注意: 下方初始化的状态还要结合transitionAppear={true}为true才可以.example-appear{    //初始化时候的状态
    opacity: 0;
} 
.example-appear.example-appear-active{ 
//初始化结束时候的状态eg: opacity: 1;
    transition: opacity 500ms ease-in;
}
Copy after login

Click to view more information...

Eight: React Router (react-router)

Basic usage code record:

//首先是引入
import { Route,Router,browserHistory } from &#39;react-router&#39;
render(){
    return(
        //这里使用了browserHistory优化了路径,路径上就不会有#了        <Router history={browserHistory}>
            <Route path="/" compontent={ AppContainer }>
                //指定默认情况下加载的子组件                <IndexRoute component={ HomeContainer }/>
                <Route path="home" component={ HomeContainer } />
                <Route path="about" component={ AboutContainer } />
                <Route path="list" component={ ListContainer }>
                    <Route path="detail" component={ DetailContainer }/>
                </Route>
            </Route>
        </Router>
    )
}
Copy after login

Note: About the difference between browserHistory and hashHistory

1.browserHistory is not supported in lower version browsers. But hashHistory supports
2. When using browserHistory, you can’t access it by directly copying and pasting the link into a new page, but hashHistory can
3. If you use browserHistory, # will not appear on the address bar, but when you use hashHistory, it will A # sign appears
4. The browserHistory component will only be executed once during execution, while the hashHistory component will be executed twice. In this case, there may be problems with the operations of some life cycle functions

Prerequisite: Cooperation Webpack works together to achieve on-demand loading: that is, in addition to the components required for the homepage, other components are loaded only after being accessed. . .

The code implementation is to rewrite the component in the previously written route: Let’s list about this one

import { Route,Router,browserHistory } from &#39;react-router&#39;render(){    return(        //这里使用了browserHistory优化了路径,路径上就不会有#了
        <Router history={browserHistory}>
            <Route path="/" compontent={ AppContainer }>                //指定默认情况下加载的子组件
                <IndexRoute component={ HomeContainer }/>
                <Route path="home" getComponent={ 
                    (nextState,callback) => {                        require.ensure([],(require) => {
                            callback(null,require(&#39;组件路径地址&#39;).default)
                        },"自定义一个名字")
                    }
                }
                 />
                <Route path="list" component={ ListContainer }>
                    <Route path="detail" component={ DetailContainer }/>
                </Route>
            </Route>
        </Router>
    )
}
Copy after login

Learn more about on-demand loading~

9: fetch request service

About fetch

If you want to use jsonp, install fetch-jsonp

10: Get path parameters and query string

Path Parameters:

this.props.params.参数名
Copy after login

Query string:

this.props.location.query.参数名
Copy after login
This article ends here (if you want to see more, go to the PHP Chinese website

React User Manual column to learn ), if you have any questions, you can leave a message below.

The above is the detailed content of A collection of simple and practical knowledge points about React (with example code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template