首页 > 解决方案 > 更新 React 组件中前导空格的状态

问题描述

export class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      value: "content",
      errorMessage: "this is a required field",
      required: true
    };
  }
  render() {
    const updateValue = val => {
      this.setState({ value: val.target.value });
    };

    const handleClick = () => {
      if (this.state.value.trim() === "") {
        this.setState({ errorMessage: "Cant have leading whitespace" });
      }
    };

    return (
      <div className="App">
        <input
          onChange={updateValue}
          value={this.state.value}
          type="text"
          required={this.state.required}
        />
        {this.state.value.length < 1 ? (
          <div>{this.state.errorMessage}</div>
        ) : null}
        <button onClick={handleClick}>OK</button>
      </div>
    );
  }
}

errorMessage如果输入为空,我有上面的组件呈现状态。我还尝试更新此errorMessage状态以读取"Cant have leading whitespace"用户是否用空白填充输入框并点击OK按钮。

一旦单击按钮,我期望发生的情况如下:

  if (this.state.value.trim() === "") {
    this.setState({ errorMessage: "Cant have leading whitespace" });
  }

也就是说,它检查value状态是否仅包含空字符串并errorMessage相应地更新状态。

然而,这个状态并没有像我期望的那样更新。我该如何解决这个问题?谢谢!

我在这里有一个工作演示:https ://codesandbox.io/s/2x846p0p5y

标签: reactjs

解决方案


你能像下面这样修改代码吗,也可以在这里修剪状态值

{this.state.value.trim().length < 1 ? (
      <div>{this.state.errorMessage}</div>
 ) : null}

推荐阅读