首页 > 解决方案 > 反应:无法读取未定义的属性“值”

问题描述

我正在尝试制作一个 React 计算器。我正在为初始测试构建组件,但我似乎无法编译它。我认为我没有将状态作为道具正确地传递给 Display 组件,但我真的不知道我做错了什么。

import React, { Component } from "react";
import "./App.css";

class Calculator extends Component {
  constructor(props) {
    super(props);
    this.state = { value: "[]" };
  }

  render() {
    return (
      <div id="container">
        <Button value={"1"} type="input" />
        <Button value={"2"} type="input" />
        <Button value={"3"} type="input" />
        <Button value={"4"} type="input" />
        <Button value={"5"} type="input" />
        <Button value={"6"} type="input" />
        <Button value={"7"} type="input" />
        <Button value={"8"} type="input" />
        <Button value={"9"} type="input" />
        <Button value={"."} type="input" />
        <Button value={"="} type="input" />
        <Button value={"Clear"} type="input" />
        <Button value={"add"} type="input" />
        <Button value={"substract"} type="input" />
        <Button value={"multiply"} type="input" />
        <Button value={"divide"} type="input" />
        <Display value={this.state.value} />
      </div>
    );
  }
}

const Button = props => {
  return <input type="Button" value={props.value} />;
};

const Display = props => {
  return (
    <div>
      <p>{props.state.value}</p>
    </div>
  );
};

标签: reactjs

解决方案


value提供给您的组件 的道具Display将被调用value,而不是state.value

const Display = props => {
  return (
    <div>
      <p>{props.value}</p>
    </div>
  );
};

推荐阅读