首页 > 解决方案 > Nextjs 上的 ContentEditable,更新未显示在状态

问题描述

我有一个消息组件。我有一个 ContentEditable 组件https://www.npmjs.com/package/react-contenteditable我在那里使用,因为我需要在这个“textarea”中添加联系人,但我需要在里面实现 html 代码来分隔每个标签,给它们是一种颜色,等等。

问题是我想阻止字符,用户将无法添加字母,只能添加数字、逗号和空格。我为此创建了一个函数以使用“onChange”,它在控制台中向我显示了正确的数据。但是在框架中它仍然显示用户输入的非法字符。正确的数据处于状态,但它不会在 ContentEditable 框架上更新。


  const contentEditable = React.createRef();
  let state = { html: "0424" };

  const handleChange = evt => {


    let htmlf = evt.target.value.replace(/\D/g,''); ;
    console.log(htmlf);
    state = { html: htmlf };
    console.log(state);
  };



        <ContentEditable
          innerRef={contentEditable}
          html={state.html} // innerHTML of the editable div
          disabled={false} // use true to disable editing
          onChange={handleChange} // handle innerHTML change
          tagName="numero" // Use a custom HTML tag (uses a div by default)
          id="contacts"
        />

解决方案

只需以不同的方式声明组件状态。

constructor(props) {
    super(props);

    this.state = {
      html: "0424"
    };

  }

  contentEditable = React.createRef();

  handleChange = evt => {
    let htmlf = evt.target.value.replace(/\D/g, "");
    console.log(htmlf);
    this.setState({ html: htmlf })
    console.log(this.state);
  };

<ContentEditable
            innerRef={this.contentEditable}
            html={this.state.html} // innerHTML of the editable div
            disabled={false} // use true to disable editing
            onChange={this.handleChange} // handle innerHTML change
            tagName="numero" // Use a custom HTML tag (uses a div by default)
            id="contacts"
          />



标签: javascripthtmlreactjscontenteditablenext.js

解决方案


推荐阅读