Skip to content

编写 ToDoList 列表

根据官网提示自行安装 create-react-app 项目。

编写 HelloWord 组件

react 编写组件提供两种方式,一种为 class 组件形式,也叫有状态组件;一种为 function 组件形式,也叫做无状态组件。

其中,class 组件形式如下:

import React, {Component} from 'react'

    class HelloWord extends Component() {
        constructor(props) {
            super(props)
        }

        return <div>Hello Word</div>
    }
import React, {Component} from 'react'

    class HelloWord extends Component() {
        constructor(props) {
            super(props)
        }

        return <div>Hello Word</div>
    }

function 组件形式如下:

import React from 'react'

    function HelloWord() {
        return <div>Hello Word</div>
    }
import React from 'react'

    function HelloWord() {
        return <div>Hello Word</div>
    }

如果返回内容为多行,可以在 return 后添加 ( ...代码 )class 组件也是如此, 即:

import React from 'react'

    function HelloWord() {
        return (
            <div>Hello Word</div>
        )
    }
import React from 'react'

    function HelloWord() {
        return (
            <div>Hello Word</div>
        )
    }

JXS 语法

react 组件中使用 JXS 注释内容有两种方式;

  • 一种为单行注释
import React from 'react'

    function HelloWord() {
        return (
            // 注释
            <div>Hello Word</div>
        )
    }
import React from 'react'

    function HelloWord() {
        return (
            // 注释
            <div>Hello Word</div>
        )
    }
  • 一种为多行注释
import React from 'react'

    // function 组件
    function HelloWord() {
        return (
            {/*
                注释
            */}
            <div>Hello Word</div>
        )
    }
import React from 'react'

    // function 组件
    function HelloWord() {
        return (
            {/*
                注释
            */}
            <div>Hello Word</div>
        )
    }

编写标签,给标签添加类名需要注意使用 className,即

import React from 'react'

    function HelloWord() {
        return (
            <div className="box">Hello Word</div>
        )
    }
import React from 'react'

    function HelloWord() {
        return (
            <div className="box">Hello Word</div>
        )
    }

使用 label 时,注意使用 htmlFor,即:

import React from 'react'

    function HelloWord() {
        return (
            <div>
                <label htmlFor="fename"></label>
                <input type="text" name="name" id="fename" />
            </div>
        )
    }
import React from 'react'

    function HelloWord() {
        return (
            <div>
                <label htmlFor="fename"></label>
                <input type="text" name="name" id="fename" />
            </div>
        )
    }

解析 html 标签内容使用 dangerouslySetInnerHTML,即:

import React from 'react'

    const html = "<h2>标签</h2>"

    function HelloWord() {
        return (
            <div dangerouslySetInnerHTML={{_html:html}}></div>
        )
    }
import React from 'react'

    const html = "<h2>标签</h2>"

    function HelloWord() {
        return (
            <div dangerouslySetInnerHTML={{_html:html}}></div>
        )
    }

编写 ToDoList 组件

import React, {Component} from 'react'

    class ToDoList extends Component{
        constructor(props) {
            super(props)

        }

        return (
            <ul>
                <li>内容一</li>
                <li>内容二</li>
            </ul>
        )
    }

    export default ToDoList
import React, {Component} from 'react'

    class ToDoList extends Component{
        constructor(props) {
            super(props)

        }

        return (
            <ul>
                <li>内容一</li>
                <li>内容二</li>
            </ul>
        )
    }

    export default ToDoList

编写完成,在该项目根目录 index.js 引入该组件后在界面可查看内容。

删除 ToDoList

import React, {Component} from 'react'

    class ToDoList extends Component{
        constructor(props) {
            super(props)
            this.state={
                list: ['内容一', '内容二']
            }
        }

        return (
            <ul>
                {
                    this.state.list.map((item, index) => {
                        return (
                            <li 
                                key={item+index} 
                                onClick="this.deleteItem.bind(this, index)">
                                {item}
                            </li>
                        )
                    })
                }
            </ul>
        )

        deleteItem(index) {
            let list = this.state.list;
            list.splice(1, index);
            this.setState({
                list: list
            })
        }
    }

    export default ToDoList
import React, {Component} from 'react'

    class ToDoList extends Component{
        constructor(props) {
            super(props)
            this.state={
                list: ['内容一', '内容二']
            }
        }

        return (
            <ul>
                {
                    this.state.list.map((item, index) => {
                        return (
                            <li 
                                key={item+index} 
                                onClick="this.deleteItem.bind(this, index)">
                                {item}
                            </li>
                        )
                    })
                }
            </ul>
        )

        deleteItem(index) {
            let list = this.state.list;
            list.splice(1, index);
            this.setState({
                list: list
            })
        }
    }

    export default ToDoList

添加 ToDoList 列表内容

import React, {Component} from 'react'

    class ToDoList extends Component{
        constructor(props) {
            super(props)
            this.state={
                inputVal: '',
                list: ['内容一', '内容二']
            }
        }

        return (
            <>
                <input type="text" 
                    value={inputVal} 
                    onChange={this.changeItem.bind(this)} />
                <button onClick={this.addItem.bind(this)}>click me</button>
                <ul>
                    {
                        this.state.list.map((item, index) => {
                            return (
                                <li 
                                    key={item+index} 
                                    onClick="this.deleteItem.bind(this, index)">
                                    {item}
                                </li>
                            )
                        })
                    }
                </ul>
            </input>
        )

        changeItem(e) {
            this.setState({
                inputVal: e.target.value
            })
        }
        
        addItem() {
            this.setState({
                list: [...this.state.list, this.state.inputVal],
                inputVal: ''
            })
        }

        deleteItem(index) {
            let list = this.state.list;
            list.splice(1, index);
            this.setState({
                list: list
            })
        }
    }

    export default ToDoList
import React, {Component} from 'react'

    class ToDoList extends Component{
        constructor(props) {
            super(props)
            this.state={
                inputVal: '',
                list: ['内容一', '内容二']
            }
        }

        return (
            <>
                <input type="text" 
                    value={inputVal} 
                    onChange={this.changeItem.bind(this)} />
                <button onClick={this.addItem.bind(this)}>click me</button>
                <ul>
                    {
                        this.state.list.map((item, index) => {
                            return (
                                <li 
                                    key={item+index} 
                                    onClick="this.deleteItem.bind(this, index)">
                                    {item}
                                </li>
                            )
                        })
                    }
                </ul>
            </input>
        )

        changeItem(e) {
            this.setState({
                inputVal: e.target.value
            })
        }
        
        addItem() {
            this.setState({
                list: [...this.state.list, this.state.inputVal],
                inputVal: ''
            })
        }

        deleteItem(index) {
            let list = this.state.list;
            list.splice(1, index);
            this.setState({
                list: list
            })
        }
    }

    export default ToDoList

父子组件传值

父组件:

import React, {Component} from 'react'

    import ToDoListItem from 'ToDoListItem'

    class ToDoList extends Component{
        constructor(props) {
            super(props)
            this.state={
                inputVal: '',
                list: ['内容一', '内容二']
            }
        }

        return (
            <>
                <input type="text" 
                    value={inputVal} 
                    onChange={this.changeItem.bind(this)} />
                <button onClick={this.addItem.bind(this)}>click me</button>
                <ul>
                    {
                        this.state.list.map((item, index) => {
                            return (
                                <ToDoListItem 
                                    index={index}
                                    content={item} 
                                    deleteItem={this.deleteItem.bind(this)}
                                    key={item+index} />
                            )
                        })
                    }
                </ul>
            </input>
        )

        changeItem(e) {
            this.setState({
                inputVal: e.target.value
            })
        }
        
        addItem() {
            this.setState({
                list: [...this.state.list, this.state.inputVal],
                inputVal: ''
            })
        }

        deleteItem(index) {
            let list = this.state.list;
            list.splice(1, index);
            this.setState({
                list: list
            })
        }
    }

    export default ToDoList
import React, {Component} from 'react'

    import ToDoListItem from 'ToDoListItem'

    class ToDoList extends Component{
        constructor(props) {
            super(props)
            this.state={
                inputVal: '',
                list: ['内容一', '内容二']
            }
        }

        return (
            <>
                <input type="text" 
                    value={inputVal} 
                    onChange={this.changeItem.bind(this)} />
                <button onClick={this.addItem.bind(this)}>click me</button>
                <ul>
                    {
                        this.state.list.map((item, index) => {
                            return (
                                <ToDoListItem 
                                    index={index}
                                    content={item} 
                                    deleteItem={this.deleteItem.bind(this)}
                                    key={item+index} />
                            )
                        })
                    }
                </ul>
            </input>
        )

        changeItem(e) {
            this.setState({
                inputVal: e.target.value
            })
        }
        
        addItem() {
            this.setState({
                list: [...this.state.list, this.state.inputVal],
                inputVal: ''
            })
        }

        deleteItem(index) {
            let list = this.state.list;
            list.splice(1, index);
            this.setState({
                list: list
            })
        }
    }

    export default ToDoList

子组件:

import React, {Component} from 'react'

    class TodoListItem extends Component{
        constructor(props) {
            super(props)
        }

        shouldComponentUpdate(nextProps, nextState) {
            if(this.props.content !== nextState.content) return true
        }

        return (
            <li onClick={this.deleteItem.bind(this)}>
                {this.props.content}
            </li>
        )

        deleteItem() {
            this.props.deleteItem(this.props.index)
        }
    }

    export default TodoListItem
import React, {Component} from 'react'

    class TodoListItem extends Component{
        constructor(props) {
            super(props)
        }

        shouldComponentUpdate(nextProps, nextState) {
            if(this.props.content !== nextState.content) return true
        }

        return (
            <li onClick={this.deleteItem.bind(this)}>
                {this.props.content}
            </li>
        )

        deleteItem() {
            this.props.deleteItem(this.props.index)
        }
    }

    export default TodoListItem

PropsTypes 校验传递的值

import React, {Component} from 'react'
    import PropTypes from 'prop-types'

    class TodoListItem extends Component{
        constructor(props) {
            super(props)
        }

        return (
            <li onClick={this.deleteItem.bind(this)}>
                {this.props.content}
            </li>
        )

        deleteItem() {
            this.props.deleteItem(this.props.index)
        }
    }

    TodoListItem.propTypes = {
        content: PropTypes.string
    }

    /*
    TodoListItem.defaultProp = {
        content: '今天天气很不错~'
    }
    */

    export default TodoListItem
import React, {Component} from 'react'
    import PropTypes from 'prop-types'

    class TodoListItem extends Component{
        constructor(props) {
            super(props)
        }

        return (
            <li onClick={this.deleteItem.bind(this)}>
                {this.props.content}
            </li>
        )

        deleteItem() {
            this.props.deleteItem(this.props.index)
        }
    }

    TodoListItem.propTypes = {
        content: PropTypes.string
    }

    /*
    TodoListItem.defaultProp = {
        content: '今天天气很不错~'
    }
    */

    export default TodoListItem

ref属性

使用 ref 获取值。

import React, {Component} from 'react'

    class ToDoList extends Component{
        constructor(props) {
            super(props)

            this.state={
                inputVal: '',
                list: []
            }
        }

        return (
            <>
                <input type="text" 
                    value={inputVal} 
                    ref={(input) => {this.input=input}}
                    onChange={this.changeItem.bind(this)} />
                <button onClick={this.addItem.bind(this)}>click me</button>
                <ul>
                    {
                        this.state.list.map((item, index) => {
                            return <li key={index+item}>{item}</li>
                        })
                    }
                </ul>
            </>
        )

        changeItem() {
            this.setState({
                inputVal: this.input.value
            }, () => {
                // 回调函数中获取最新list数据 ...
            })
        }

        addItem() {
            this.setState({
                list: [...this.state.list, this.state.inputVal],
                inputVal: ''
            })
        }
    }
import React, {Component} from 'react'

    class ToDoList extends Component{
        constructor(props) {
            super(props)

            this.state={
                inputVal: '',
                list: []
            }
        }

        return (
            <>
                <input type="text" 
                    value={inputVal} 
                    ref={(input) => {this.input=input}}
                    onChange={this.changeItem.bind(this)} />
                <button onClick={this.addItem.bind(this)}>click me</button>
                <ul>
                    {
                        this.state.list.map((item, index) => {
                            return <li key={index+item}>{item}</li>
                        })
                    }
                </ul>
            </>
        )

        changeItem() {
            this.setState({
                inputVal: this.input.value
            }, () => {
                // 回调函数中获取最新list数据 ...
            })
        }

        addItem() {
            this.setState({
                list: [...this.state.list, this.state.inputVal],
                inputVal: ''
            })
        }
    }

生命周期函数

生命周期函数就是在某一时刻自动执行的函数。

  • 初始化阶段 (Initialization

  • 挂载阶段(Mounting

  • componentWillMount:组件即将挂在界面前执行。
componentWillMount() {
        console.log(`componentWillMount`)
    }
componentWillMount() {
        console.log(`componentWillMount`)
    }
  • render:页面 propsstate 发生变化时执行。
render() {
        console.log(`render`)
    }
render() {
        console.log(`render`)
    }
  • componentDidMount:组件挂在完成时执行。
componentDidMount() {
        console.log(`componentDidMount`)
    }
componentDidMount() {
        console.log(`componentDidMount`)
    }
  • 请求接口可以放在该生命周期中。

  • 更新阶段 (Updation

  • shouldComponentUpdate:在组件更新前自动执行。
shouldComponentUpdate() {
        console.log(`shouldComponentUpdate`)
        return true
    }
shouldComponentUpdate() {
        console.log(`shouldComponentUpdate`)
        return true
    }

要求必须返回布尔值。

  • componentWillUpdate:组件更新时执行。
componentWillUpdate() {
        console.log(`componentWillUpdate`)
    }
componentWillUpdate() {
        console.log(`componentWillUpdate`)
    }
  • componentDidUpdate:组件更新后执行。
componentDidUpdate() {
        console.log(`componentDidUpdate`)
    }
componentDidUpdate() {
        console.log(`componentDidUpdate`)
    }
  • componentWillReceiveProps:在子组件中使用,子组件接收 prop 该函数就会执行。
componentWillReceiveProps() {
        console.log(`componentWillReceiveProps`)
    }
componentWillReceiveProps() {
        console.log(`componentWillReceiveProps`)
    }
  • 子组件接收到父组件传递过来的参数,父组件render函数重新被执行,这个生命周期就会被执行。

  • 也就是说这个组件第一次存在于Dom中,函数是不会被执行的;

  • 如果已经存在于Dom中,函数才会被执行。