0

咬人猫

背景:
<TextArea>onChange方法中使用setState来保存value的话,会导致输入卡顿,原因是用户在输入时,一直在setState,导致整个页面一直重新渲染

主页面:

import React, {
  Component,
} from 'react';
import { Input } from 'antd';

const { TextArea } = Input;

class CustomCompent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      targetValue: '',
    };
  }

   handleChange = e => {
      let targetValue = e.target.value;
      this.setState({
        targetValue,
      });
    };

    render() {
      const { targetValue } = this.state;

      return (
        <>
          xxxx
          xxxx
          <TextArea
            onChange={this.handleChange}
            value={targetValue}
          />
          <p>{targetValue.length}/100</p>
        </>
      );}

解决方法:
<TextArea>组件单独封装成一个组件(component),这样就只会触发自身重新渲染而不是整个页面!

TextArea 组件:

import React from 'react';
import { Input } from 'antd';

const { TextArea } = Input;

class CountTextArea extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      targetValue: '',
    };
  }

  handleChange = value => {
    let targetValue = value.target.value;
    this.setState({
      targetValue,
    });
  };

  render() {
    const {  setRef } = this.props;
    const { targetValue } = this.state;

    return (
      <>
        <TextArea
          onChange={this.handleChange}
          value={targetValue}
          ref={setRef}
        />
        <p>{targetValue.length}/100</p>
      </>
    );
  }
}

export default CountTextArea;

主页面:

import React, {
  Component,
} from 'react';
import { Button } from 'antd';
import CountTextArea from './CountTextArea';

class CustomCompent extends Component {
  componentDidMount() {
    this.customTextArea = React.createRef();
  }

  handleOk = () => {
    if (this.customTextArea && this.customTextArea.current) {
      //发送内容
      let value =this.customTextArea.current.textAreaRef.value
      //xxx
    }
  }

  render() {

    return (
      <>
        <CountTextArea
          handleOk={this.handleOk}
          setRef={this.customTextArea}
        />
        <Button onClick={this.handleOk}>发送</Button>
      </>
    );
  }
}

这样就可以让用户愉快地输入的同时,setState textarea 的值啦~


(完)

你可能感兴趣的

载入中...