【问题标题】:How to get reactJS to render a state variable如何让 reactJS 呈现状态变量
【发布时间】:2020-04-18 10:12:06
【问题描述】:

我刚刚开始研究反应形式。我遇到了一个问题,react 在我的渲染中标记了我尝试填充输入框标签的行。这是我的应用程序的代码:

import React, { Component } from 'react';
import './App.css';
import { Container, Row, Col, Input, Button, Fa, Card, CardBody } from 'mdbreact';


class App extends Component {

  constructor(props) {
    super(props);
    this.state = { 
      name: {
        valid: true,
        value: '',
        label: 'Your Name',
        length: 0
      }
    }

    this.saveData = this.saveData.bind(this);
  } 

  saveData() {

    let currentComponent = this;

    var validData = true;
    var locaName = {
      valid: true,
      value: '',
      label: 'Your Name',
      length: 0
    }

    locaName.value = document.getElementById("lblName").value;
    locaName.length = locaName.value.length;

    if (locaName.length < 1) {
      validData = false;
      locaName.valid = false;
      locaName.label = "You need to enter your name";
    }

    if (validData == false) {
      currentComponent.setState({ name:locaName });
    }

  }

  render() {

    return (
      <div className="App">
        <div className="d-flex flex-wrap justify-content-center position-absolute w-100 h-50 align-items-center align-content-center">
          <Container>
            <Row>
              <Col md="6">
                <Card>
                  <CardBody>
                    <form>
                      <p className="h4 text-center py-4">Sign up</p>
                      <div className="grey-text">
                        <Input id="lblName" label={this.name.label} icon="user" group type="text" />
                        <Input id="lblEmail" label="Your email" icon="envelope" group type="email" />
                        <Input id="lblConfirmEmail" label="Confirm your email" icon="exclamation-triangle" group type="text" />
                      </div>
                      <div className="text-center py-4 mt-3">
                        <Button color="cyan" onClick={() => 
                        { 
                        this.saveData();
                        }}>Save</Button>
                      </div>
                    </form>
                  </CardBody>
                </Card>
              </Col>
            </Row>
          </Container>
        </div>
      </div>
    )
  }
}

export default App;

此时,我要做的就是使用名称输入框的标签呈现表单,如果没有输入名称,则反应重新呈现带有标签的表单姓名输入框为“您需要输入您的姓名”。

非常感谢任何帮助。

【问题讨论】:

    标签: reactjs mdbreact


    【解决方案1】:

    为了引用你需要使用this.state.name的状态变量,我只在你的渲染函数中看到this.name

    【讨论】:

    • 谢谢保罗!也许我应该停止编码一段时间。这么简单的事情错过了。有一双新鲜的眼睛看看总是好的。再次感谢您。
    猜你喜欢
    • 1970-01-01
    • 2021-08-17
    • 2020-03-06
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    • 2017-06-24
    • 1970-01-01
    • 2021-12-29
    相关资源
    最近更新 更多