reactjs - 状态未从 NaN 更新
问题描述
我有一个非常简单的表格,它采用Name
and Age
。和Name
状态Age
已更新onChange
。但是,一旦我输入完姓名和年龄,在最底部,我的p
标签不会返回姓名和年龄。
我相信我的commonChange()
功能是正确的,但不确定为什么输入数据后不显示姓名和年龄。
我的代码如下:
import React from 'react';
import ReactDOM from 'react-dom';
import './normalize.css';
import './index.css';
class Form extends React.Component{
constructor(){
super();
this.state = {
nameValue: '',
ageValue: ''
}
this.commonChange = this.commonChange.bind(this);
}
commonChange(event){
this.setState(
{
[event.target.name]: event.target.value
});
}
render(){
return (
<div>
<h1>Name and Age Return</h1>
<form>
<label>Name:
<input type="text" name="nameValue" onChange={this.commonChange} />
</label><br />
<label>Age:
<input type="text" name="ageValue" onChange={this.commonChange} />
</label>
</form>
{this.props.nameValue && <p>{this.props.nameValue}</p>}
{this.props.ageValue && <p>{this.props.ageValue}</p>}
</div>
);
}
}
ReactDOM.render( < Form / > , document.getElementById('root'));
解决方案
nameValue 和 ageValue 都是组件状态的一部分,但不是 props。
道具是您从父组件接收数据到子组件的东西。状态是您在组件中管理的东西。
所以改变
{this.props.nameValue && <p>{this.props.nameValue}</p>}
{this.props.ageValue && <p>{this.props.ageValue}</p>}
到
{this.state.nameValue && <p>{this.state.nameValue}</p>}
{this.state.ageValue && <p>{this.state.ageValue}</p>}
推荐阅读
- javascript - 添加和删除类数组错误
- css - 带有修复页脚和导航的 Bootstrap 4 全屏页面:内容不会填充和溢出
- recursion - 不安全的 Rust 中的堆栈引用,但确保不安全不会从堆栈中泄漏?
- c# - 我如何在不同的包中获取路线
- ios - 从 DateFormatter 检索使用“AM/PM”格式指示时间的“本地化”字符串时遇到问题
- vega-lite - 热图中的文本叠加
- javascript - 我可以使用 Promise.all 同时从 firestore 获取一些文件吗?
- c++ - 了解 C++ 映射为什么不使用 clear() 释放堆内存?
- android-studio - 没有虚拟化硬件支持的 Android 虚拟设备?
- go - 为什么按位运算符比 Go 中的除法和模运算慢?