• React生命周期, 兄弟组件之间通信


    1、一个demo(https://www.reactjscn.com/docs/state-and-lifecycle.html)

    class Clock extends React.Component {
        constructor(props) {
          super(props);
          this.state = {date: new Date()};
        }
      
        componentDidMount() {
          this.timerID = setInterval(
            () => this.tick(),
            1000
          );
        }
      
        componentWillUnmount() {
          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>
          );
        }
      }
      
      ReactDOM.render(
        <Clock />,
        document.getElementById('root')
      );

    2、demo: 兄弟组件之间通信,使用到生命周期钩子componentWillReceiveProps

    项目结构:

    demo效果:“搜索组件”传递keyword参数给父组件,然后父组件将keyword参数传递给“显示子组件”

    App.jsx

    import React from 'react'
    import UserSearch from '../user-search/UserSearch.jsx'
    import UserList from '../user-list/UserList.jsx'
    
    export default class App extends React.Component {
        constructor(props) {
            super(props)
            this.state = {
                keyword: ''
            }
    
            this.setKeyword = this.setKeyword.bind(this)
        }
    
        setKeyword(keyword) {
            console.log(`App组件setKeyword被调用, keyword=${keyword}`)
            this.setState({ keyword })
        }
    
        render() {
            return (
                <div>
                    <UserSearch setKeyword={this.setKeyword} />
                    <UserList keyword={this.state.keyword} />
                </div>
            )
        }
    }

      

      UserSearch.jsx

    import React from 'react'
    import PropTypes from 'prop-types'
    
    export default class UserSearch extends React.Component {
        state = {
            keyword: ''
        }
    
        static propTypes = {
            setKeyword: PropTypes.func.isRequired
        }
    
        render() {
            const { keyword} = this.state
            return (
                <div>
                    <h3>搜索用户</h3>
                    <input type="text" placeholder="请输入搜索关键字" name="keyword" value={keyword} onChange={(e) => this.keywordInputOnChangeHandler(e)} />
                    <input type="button" value="开始搜索" onClick={() => this.searchClickHandler()} />
                </div>
            )
        }
    
        keywordInputOnChangeHandler = (e) => {
            const keyword = e.target.value
            this.setState({ keyword })
        }
    
        searchClickHandler = () => {
            const { keyword } = this.state
            console.log(`keyword.trim()=${keyword.trim()}`)
            if (!keyword.trim()) return
            this.props.setKeyword(keyword)
        }
    }

      UserList.jsx

    import React from 'react'
    import PropTypes from 'prop-types'
    import Axios from 'axios'
    
    export default class UserList extends React.Component {
        state = {
            userList: []
        }
    
        componentWillReceiveProps(newProps) {
            const { keyword } = newProps
            Axios.get(`http://localhost:4000/react-db-crud/user/search?keyword=${keyword}`)
                .then(res => {
                    if (res.data.code == 0) {
                        const userList = res.data.data
                        console.log(`userList=${JSON.stringify(userList)}`)
                        this.setState({ userList })
                    }
                })
        }
    
        render() {
            return (
                <div>
                    {
                        this.state.userList.map(user => <p>{user.id + "--" + user.name + "--" + user.age}</p>)
                    }
                </div>
            )
        }
    }
    
    UserList.propTypes = {
        keyword: PropTypes.string.isRequired
    }
  • 相关阅读:
    error: xslt-config not found. Please reinstall the libxslt >= 1.1.0 distribution
    configure: error: Cannot find OpenSSL's libraries
    PHP编译configure时常见错误
    解决PHP编译cURL的reinstall the libcurl问题
    Linux环境PHP7.0安装
    PHP 7的一些引人注目的新特性简单介绍
    (转).net webconfig使用IConfigurationSectionHandler自定section
    Asp.Net MVC 使用FileResult导出Excel数据文件
    ASP.NET MVC:通过 FileResult 向 浏览器 发送文件
    [老老实实学WCF] 第十篇 消息通信模式(下) 双工
  • 原文地址:https://www.cnblogs.com/xy-ouyang/p/12034424.html
Copyright © 2020-2023  润新知