[React]面向组件编程

1. 定义组件

- 函数式定义(简单组件),使用function定义

import React from 'react';
import ReactDOM from 'react-dom/client';

function App() {
  return (
    <button onClick={handleClick}>click</button> // 直接把方法handleClick赋值给onClick
  )
  
  function handleClick() {
    alert('click')
  }
}
export default App; // 其他组件引用时需要export出去

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

- 类式定义(复杂组件),使用class定义

import React from 'react';
import ReactDOM from 'react-dom/client';

class App extends React.Component {
  render() {
    return (
      <button onClick={this.handleClick}>click</button>  // this代表在App的实例对象上赋值handleClick
    )
  }
  handleClick() {
    alert('click')
  }
}
export default App; // 其他组件引用时需要export出去

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

2. state,设置组件初始值

- 原始定义,需要在constructor中定义state和绑定方法handleClick的this

class Weather extends React.Component {
  // 创建构造器,类似ruby的initialize
  constructor(props) {
  	// 构造器是否接收props,是否传递给super,取决于是否希望在构造器中通过this访问props
  	// 如果是 super(),则 console.log(this.props)为undefined, console.log(props)就是传进来的props
  	// 如果是 super(props),则 console.log(this.props)为Weather的实例
    super(props) // 调用父类React.Component的构造器
    this.state = { isHot: true, wind: 'big' }
    this.handleClick = this.handleClick.bind(this) // 给handleClick绑定this
  }

  render() {
    const isHot = this.state.isHot
    return (
      <h1 onClick={this.handleClick}>Today is very {isHot ? 'hot' : 'cold'}, wind: {this.state.wind}</h1>
    )
  }
  
  handleClick() {
    this.setState({ isHot: !this.state.isHot, wind: this.state.wind !== 'big' ? 'big' : 'small' })
  }
}

- 简化后在类中直接给state和handleClick赋值,就直接把属性和方法绑定到Weather的实例上了

class Weather extends React.Component {
  // 初始化
  state = { isHot: true, wind: 'big' }
  // 渲染
  render() {
    const isHot = this.state.isHot
    return (
      <h1 onClick={this.handleClick}>Today is very {isHot ? 'hot' : 'cold'}, wind: {this.state.wind}</h1>
    )
  }
  // 自定义方法
  handleClick = () => {
    this.setState({ isHot: !this.state.isHot, wind: this.state.wind !== 'big' ? 'big' : 'small' })
  }
}

3. props,从组件外部给组件定义中传值

- 函数式组件使用props

- 函数式组件使用props
```typescript
import React from 'react';
import ReactDOM from 'react-dom/client';
import PropTypes from 'prop-types';

function Person(props){
  const { name, age, sex } = props
  return (
    <ul>
      <li>name: {name}</li>
      <li>age: {age}</li>
      <li>sex: {sex}</li>
    </ul>
  )
}
// 限制属性
Person.propTypes = {
  name: PropTypes.string.isRequired,
  age: PropTypes.number,
  sex: PropTypes.string,
  speak: PropTypes.func
}
// 设置属性默认值
Person.defaultProps = {
  age: 18,
  sex: 'female'
}

function speak() {
  console.log('speak')
}

const root = ReactDOM.createRoot(document.getElementById('root'));
const p = { name: 'Tom' }
root.render(
  <React.StrictMode>
    {/*  */}
    <Person {...p} speak={speak} />
  </React.StrictMode>
);

- 类式组件使用props

import React from 'react';
import ReactDOM from 'react-dom/client';
import PropTypes from 'prop-types';

class Person extends React.Component {
  render() {
    const { name, age, sex } = this.props
    return (
      <ul>
        <li>name: {name}</li>
        <li>age: {age}</li>
        <li>sex: {sex}</li>
      </ul>
    )
  }
  state = { isHot: true } // 这是给组件实例对象赋值
  // 限制属性 前面加 static 是给组件类赋值
  static propTypes = {
    name: PropTypes.string.isRequired,
    age: PropTypes.number,
    sex: PropTypes.string,
    speak: PropTypes.func
  }
  // 设置属性默认值
  static defaultProps = {
    age: 18,
    sex: 'female'
  }
}

function speak() {
  console.log('speak')
}

const root = ReactDOM.createRoot(document.getElementById('root'));
const p = { name: 'Tom' }
root.render(
  <React.StrictMode>
    {/*  */}
    <Person {...p} speak={speak} />
  </React.StrictMode>
);

4. refs,获取其他html元素的dom,相当于$(‘#xx’)

- 字符串形式ref

class Demo extends React.Component {
  render() {
    return (
      <>
        <input ref="input1" type="text" />
        <button onClick={this.tipLeftInput}>Click me</button>
        <input ref="input2" onBlur={this.tiprightInput} type="text" />
      </>
    )
  }

  tipLeftInput = () => {
    alert(this.refs.input1.value);
  }
  tiprightInput = () => {
    alert(this.refs.input2.value);
  }
}

- 回调形式ref

class Demo extends React.Component {
  render() {
    return (
      <>
        <input ref={(currentNode) => { this.input1 = currentNode }} type="text" />
        {/*  this.input1 = currentNode} type="text" />  简写 */}
        <button onClick={this.tipLeftInput}>Click me</button>
        <input ref={(currentNode) => { this.rightInput = currentNode }} onBlur={this.tiprightInput} type="text" />
      </>
    )
  }

  tipLeftInput = () => {
    alert(this.input1.value);
  }
  tiprightInput = () => {
    alert(this.rightInput.value);
  }
}
  • ref回调函,如果是内联函数方式定义的,在更新过程中(更改state重新渲染render)会被执行两次,第一次传入参数null,第二次传入参数为DOM, 可以将ref回调函数定义为class的绑定函数避免上述问题。
    [React]面向组件编程_第1张图片

- createRef api创建ref , 较麻烦

class Demo extends React.Component {
  render() {
    return (
      <>
        <input ref={this.myRef1} type="text" />
        <button onClick={this.tipLeftInput}>Click me</button>
        <input ref={this.myRef2} onBlur={this.tiprightInput} type="text" />
      </>
    )
  }
  myRef1 = React.createRef()
  myRef2 = React.createRef()

  tipLeftInput = () => {
    console.log(this.myRef1.current.value);
  }

  tiprightInput = () => {
    console.log(this.myRef2.current.value);
  }
}

5. 事件处理

- button要获取input的值,使用ref

class Demo extends React.Component {
  render() {
    return (
      <>
        <input ref={this.myRef1} type="text" />
        <button onClick={this.tipLeftInput}>Click me</button>
      </>
    )
  }
  myRef1 = React.createRef()

  tipLeftInput = () => {
    console.log(this.myRef1.current.value);
  }
}

- input获取本身DOM的值,使用e.target获取dom

class Demo extends React.Component {
  render() {
    return (
      <>
        <input onBlur={this.tiprightInput} type="text" />
      </>
    )
  }
  
  tiprightInput = (e) => {
    console.log(e.target.value);
  }
}

6. 非受控组件和受控组件

- 非受控组件,使用ref取值,不建议使用

class Login extends React.Component {
  render() {
    return (
      <form onSubmit={this.submit}>
        <input type="text" name="username" ref={ref => this.username = ref} />
        <input type="text" name="password" ref={ref => this.password = ref} />
        <input type="submit" name="" />
      </form>
    )
  }

  submit = (e) => {
    e.preventDefault();
    alert(`username: ${this.username.value}, password: ${this.password.value}`)
  }
}

- 受控组件,使用state取值,建议使用

class Login extends React.Component {
  state = {
    username: '',
    password: ''
  }

  render() {
    return (
      <form onSubmit={this.submit}>
        <input type="text" name="username" onChange={this.saveUsername} />
        <input type="text" name="password" onChange={this.savePassword} />
        <input type="submit" name="" />
      </form>
    )
  }

  saveUsername = (e) => {
    this.setState({ username: e.target.value })
  }

  savePassword = (e) => {
    this.setState({ password: e.target.value })
  }

  submit = (e) => {
    e.preventDefault();
    alert(`username: ${this.state.username}, password: ${this.state.password}`)
  }
}

7.高阶函数

-上面的代码重构,onChange 调用的是saveFormdate方法return的返回值,是个函数
必须把一个函数交给onChange

class Login extends React.Component {
  state = {
    username: '',
    password: ''
  }

  render() {
    return (
      <form onSubmit={this.submit}>
        <input type="text" name="username" onChange={this.saveFormdate('username')} />
        <input type="text" name="password" onChange={this.saveFormdate('password')} />
        <input type="submit" name="" />
      </form>
    )
  }

  saveFormdate = (params) => {
    return (e) => {
      this.setState({ [params]: e.target.value })
    }
  }

  submit = (e) => {
    e.preventDefault();
    alert(`username: ${this.state.username}, password: ${this.state.password}`)
  }
}

8. 生命周期,回调函数或者叫钩子函数

  • 16版本生命周期
    [React]面向组件编程_第2张图片
class Life extends React.Component {
  // 构造器
  constructor(props) {
    console.log('constructor')
    super(props)
    this.state = { num: 0 }
  }
  // 组件挂载前调用
  componentWillMount() {
    console.log('componentWillMount')
  }
  // 询问是否更新组件调用
  shouldComponentUpdate() {
    console.log('shouldComponentUpdate')
    return true // 默认返回true
  }
  // 组件更新前调用
  componentWillUpdate() {
    console.log('componentWillUpdate')
  }
  // 组件挂载,初始化渲染、状态更新后调用
  render() {
    console.log('render')
    return (
      <>
        <h1 style={{ opacity: this.state.opacity }}>当前数字: {this.state.num}</h1>
        <button onClick={this.add}>数字+1</button>
        <button onClick={this.unmount}>卸载组件</button>
      </>
    )
  }
  // 组件更新后调用
  componentDidUpdate() {
    console.log('componentDidUpdate')
  }
  // 组件挂载后调用,调用一次
  componentDidMount() {
    console.log('componentDidMount')
  }
  // 组件卸载前调用
  componentWillUnmount() {
    console.log('componentWillUnmount')
  }


  // 数字+1调用
  add = () => {
    const { num } = this.state
    this.setState({ num: num + 1 })
  }

  // 卸载组件调用
  unmount = () => {
    root.unmount();
  }
}

9. 示例

  • axios使用
import axios from 'axios'
axios({
  method: 'post',
  url: '/user/12345',
  headers: { Token: 'xxxxx' },
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
}).then(
	res => {}
	err => {}
);

// 发起多个并发请求
function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

Promise.all([getUserAccount(), getUserPermissions()])
  .then(function (results) {
    const acct = results[0];
    const perm = results[1];
  });
  • App.js
import React, { Component } from 'react';
import Search from './components/Search'
import List from './components/List'
import { nanoid } from 'nanoid' // nanoid()取uuid
import './App.css'

export default class App extends Component {
  state = {
    data: [],
    isFirstSearch: true,
    loading: false,
    err_msg: ''
  }
  render() {
    return (
      <div className="App">
        <Search updateApp={this.updateApp} /> // 父给子传函数
        <List {...this.state} loading=false />// 父给子传数据
      </div>
    )
  }

  updateApp = (stateOjb) => {
    this.setState(stateOjb)
  }
}
  • Search组件中的 index.jsx
import React, { Component } from 'react'
import axios from 'axios';

export default class Search extends Component {
  render() {
    return (
      <div>
        <input ref={r => this.input = r} type='text' />  // 设置ref 
        <button onClick={this.handleSearch}>Search</button>
      </div>
    )
  }
  handleSearch = () => {
    this.props.updateApp({ isFirstSearch: false, loading: true })
    axios({
      url: `https://api.github.com/search/users?q=${this.input.value}`,
    }).then(
      res => {
        this.props.updateApp({ loading: false, data: res.data.items })
      },
      err => {
        this.props.updateApp({ loading: false, err_msg: err.message })
      }
    )
  }
}
  • List组件中的index.jsx
import React, { Component } from 'react'
import './index.css'

export default class List extends Component {
  render() {
    const { data, isFirstSearch, loading, err_msg } = this.props
    return (
      <div className='list'>
        {
          isFirstSearch ? 'input serach name' :
            loading ? 'loading...' :
              err_msg ? err_msg :
                data.map(item => {
                  return (
                    <div key={item.id}>
                      <img src={item.avatar_url} style={{ width: '100px', height: '100px' }} alt='avatar' />
                      <p>{item.login}</p>
                    </div>
                  )
                })
        }
      </div>
    )
  }
}
  • onChange onClick等传参数的话,用箭头函数直接传参
import React from 'react';
import './index.css'

export default class Item extends React.Component {
  state = { mouse: false }
  render() {
    const { list } = this.props;
    const { mouse } = this.state;
    return (
      <div className='item' style={{ background: mouse ? '#ddd' : '#fff' }} onMouseEnter={() => this.handleMounse(true)} onMouseLeave={() => this.handleMounse(false)}>
        <label htmlFor={list.id}>
          <input type="checkbox" onChange={(e) => this.onChange(e, list.id)} checked={list.isDone} name="" id={list.id} />
          <span>{list.name}</span>
        </label>
        <button onClick={() => this.handleDelete(list.id)} style={{ display: mouse ? 'inline-block' : 'none' }} >删除</button>
         <input type="checkbox" onChange={this.handleCheckbox} checked={checked} name="" id="" />
         // 传参时候不用箭头函数,则需要使用高阶函数去接收参数
         <input type="text" name="username" onChange={this.saveFormdate('username')} />
      </div>
    )
  }

  handleDelete = (id) => {  // 传id
    if (window.confirm('确定删除吗?')) {
      this.props.delTodo(id)
    }
  }
  onChange = (e, id) => {  // 传event和id
    this.props.updateTodo(id, e.target.checked)
  }

  handleMounse = (flag) => {  // 传参
    this.setState({
      mouse: flag
    })
  }
   handleCheckbox = (e) => { //直接拿到event
    this.props.allCheck(e.target.checked)
  }
  // 传参时候不用箭头函数,则需要使用高阶函数去接收参数
  saveFormdate = (params) => {
    return (e) => {
      this.setState({ [params]: e.target.value })
    }
  }
}

10. 使用消息订阅传递数据, 适用于任意组件互传数据

  • 订阅消息, 在componentDidMountcomponentWillUnmount 订阅和取消订阅
import React, { Component } from 'react'
import PubSub from 'pubsub-js'
import './index.css'

export default class List extends Component {
  state = {
    data: [],
    isFirstSearch: true,
    loading: false,
    err_msg: ''
  }
 
  componentDidMount() {
    this.token = PubSub.subscribe('search', (msg, stateObj) => {
      this.setState(stateObj)
    })
  }

  componentWillUnmount(){
    PubSub.unsubscribe(this.token)
  }
  render() {
    const { data, isFirstSearch, loading, err_msg } = this.state
    return (
      <div className='list'>
        {
          isFirstSearch ? 'input serach name' :
            loading ? 'loading...' :
              err_msg ? err_msg :
                data.map(item => {
                  return (
                    <div key={item.id}>
                      <img src={item.avatar_url} style={{ width: '100px', height: '100px' }} alt='avatar' />
                      <p>{item.login}</p>
                    </div>
                  )
                })
        }
      </div>
    )
  }
}
  • 发布消息
import React, { Component } from 'react'
import PubSub from 'pubsub-js'
import axios from 'axios';

export default class Search extends Component {
  render() {
    return (
      <div>
        <input ref={r => this.input = r} type='text' />
        <button onClick={this.handleSearch}>Search</button>
      </div>
    )
  }
  handleSearch = () => {
    PubSub.publish('search', { isFirstSearch: false, loading: true });
    axios({
      url: `https://api.github.com/search/users?q=${this.input.value}`,
    }).then(
      res => {
        PubSub.publish('search', { loading: false, data: res.data.items});
      },
      err => {
        PubSub.publish('search', { loading: false, data: err.message });
      }
    )
  }
}

你可能感兴趣的:(react.js,前端,前端框架)