前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >react.js避免在input/textareah中输入(setState)时重新渲染整个页面

react.js避免在input/textareah中输入(setState)时重新渲染整个页面

作者头像
进击的小进进
发布2022-03-28 15:00:39
4.9K0
发布2022-03-28 15:00:39
举报

咬人猫

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

主页面:

代码语言:javascript
复制
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 组件:

代码语言:javascript
复制
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;

主页面:

代码语言:javascript
复制
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 的值啦~

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-05-18,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 webchen 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档