reactjs - 更新 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
解决方案
你能像下面这样修改代码吗,也可以在这里修剪状态值
{this.state.value.trim().length < 1 ? (
<div>{this.state.errorMessage}</div>
) : null}
推荐阅读
- dataframe - 如何在 pyspark 中创建一个行值相同的新列?
- c - 用用户输入 C 替换值列表
- python - 如何将熊猫系列的引用传递到字典中?
- python - 如何在views.py中的API中设置.save()数据时设置ForeignKey字段
- swift - 如果 UIViewController 成功解除分配,没有保留周期?
- c# - 使用 MVVM 编辑时克隆要查看的对象
- c# - .SaveChanges() 不保存到数据
- azure-devops - Azure DevOps:使用作业矩阵变量填充安全文件引用
- mongodb - MongoDB 无法连接连接超时:通过 Atlas 连接
- flutter - 键盘在颤动中阻碍屏幕