首页 > 解决方案 > 如何在 reactjs 事件期间禁用和启用文本字段?

问题描述

我正在尝试使用 ReactJS 禁用和启用文本字段。

场景是:

  1. 使用输入文本并点击回车
  2. 必须禁用文本字段以防止输入新数据
  3. 文本被发送到服务器保存
  4. 保存后必须再次启用文本框。

问题是setState在 ReactJS 中的单个事件期间通过函数更新字段两次是不可能的,因为它只在完成相关事件后更新一次。那么,如何在事件期间更新输入字段两次?

我也尝试this.forceUpdate()在 each 之后使用this.setState(...),但它没有用。

theEvent(e){
  if(e.key==='Enter'){
    this.setState({newTypePredefinedValue: ''});
    this.setState({readOnly:true})
    this.forceUpdate();

    fetch(..., { ... })
      .then(() => this.componentDidMount() )
      .then(this.setState({readOnly:false}))
      .then(this.forceUpdate());
  }
}

我正在寻找一种在活动期间禁用和启用所需字段的方法。

标签: javascriptreactjs

解决方案


请注意,您正在使用

.then(this.setState({readOnly:false}))

代替

.then(() => this.setState({readOnly:false}))

这会导致第二个setState被立即调用,而不是在响应到达并且您处理它时。

你也不应该打电话forceUpdate

示例场景

密码笔

class Element extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      readOnly: false,
      input: '',
    }

    this.handleFetch = this.handleFetch.bind(this);
    this.handleInput = this.handleInput.bind(this);
  }

  handleInput(e) {
    this.setState({
      input: e.target.value
    });
  }

  handleFetch(e) {
    e.preventDefault();

    this.setState({
      readOnly: true
    });

    setTimeout(() => {
      this.setState({
        readOnly: false
      })
    }, 4000);

    /* You should use in your actual code

    fetch(..., { ... })
      .then(res => {
        // Handle response

        this.setState({
          readOnly:false
        })
      });

    */

  }

  render() {
    return (
      <div>
        <button onClick={this.handleFetch}>Click me!</button>
        <input type="text" disabled={this.state.readOnly} />
      </div>
    )
  }
}

您的函数代码已重写,如示例代码所示。

theEvent(e){
  if(e.key === 'Enter') {
    this.setState({
      newTypePredefinedValue: '',
      readOnly:true
    });

    fetch(..., { ... })
      .then(res => {
        // Handle response
        this.setState({
          readOnly:false
        })
      });
  }
}

推荐阅读