onKeyUp 在反应中不起作用,而 onChange 做了 [英] onKeyUp not working in React where onChange did

查看:24
本文介绍了onKeyUp 在反应中不起作用,而 onChange 做了的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个 React 编码挑战,需要在 KeyUp 上更新一个值.我最初将它设置为更新 onChange,但测试需要 onKeyUp,所以我尝试将其更改为更新,但我的字段不再更新,我无法在 textarea 中输入任何内容.

I'm doing a React coding challenge that requires a value to be updated onKeyUp. I initially set it to update onChange but the tests require onKeyUp so I tried to change it to that, but my fields are no longer updating and I can't type anything into the textarea.

class MarkdownApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: ''
    };

    this.handleKeyUp = this.handleKeyUp.bind(this);
  }

  handleKeyUp(event) {
    this.setState({ value: event.target.value })
  }

  render() {
    return (
      <form>
        <label>
          Enter your markdown here:
          <br />
          <textarea value={this.state.value} onKeyUp={this.handleKeyUp} id='editor' />
          <br />
        </label>
        <label>
          Your markup will be previewed here:
          <p id='preview'>{marked(this.state.value)}</p>
        </label>
      </form>
    );
  }
}

ReactDOM.render(
  <MarkdownApp />,
  document.getElementById('root')
);

就像我说的,当它是 onChange 并且我的函数是 handleChange 时,这很好用,但是因为我切换了它,所以我无法输入任何内容.

Like I said, this worked fine when it was onChange and my function was handleChange, but since I switched it I can't type anything.

推荐答案

我只想从 textarea 中删除 value 属性.因为如果您将 value 属性放入其中,则用户将无法以交互方式更改它.该值将始终保持固定(除非您明确更改代码中的值).你不需要用 React 来控制它——DOM 会为你保存值.

I would just remove the value attribute from the textarea. Because if you put the value attribute to it then the user won't be able to change it interactively. The value will always stay fixed(unless you explicitly change the value in your code). You don't need to control that with React--the DOM will hold onto the value for you.

我在下面所做的唯一更改是从 textarea 元素中删除 value={this.state.value}:

The only change I've made below is to remove value={this.state.value} from the textarea element:

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

class MarkdownApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: ''
    };

    this.handleKeyUp = this.handleKeyUp.bind(this);
  }

  handleKeyUp(event) {
    this.setState({ value: event.target.value })
  }

  render() {
    return (
      <form>
        <label>
          Enter your markdown here:
          <br />
          <textarea value={this.state.value} onKeyUp={this.handleKeyUp} id='editor' />
          <br />
        </label>
        <label>
          Your markup will be previewed here:
          <p id='preview'>{this.state.value}</p>
        </label>
      </form>
    );
  }
}

ReactDOM.render(
  <MarkdownApp />,
  document.getElementById('root')
);

这篇关于onKeyUp 在反应中不起作用,而 onChange 做了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆