首页 > 解决方案 > 状态未从 NaN 更新

问题描述

我有一个非常简单的表格,它采用Nameand 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'));

标签: reactjs

解决方案


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>}

推荐阅读