首页 > 解决方案 > 在 React 中将数据传递给组件(道具)

问题描述

我有一个 Counters 组件和一个 Counter 组件。Counters 类在下面,将四个 Counter 组件呈现到一个页面并设置它们的初始值。

import React, { Component } from "react";
import Counter from "./counter";
import Paper from '@material-ui/core/Paper';
import shadows from "@material-ui/core/styles/shadows";
import extendedIcon from "@material-ui/core/styles/shadows";

    class Counters extends Component {
      state = {
        counters: [
          { id: 1, value: 2 },
          { id: 2, value: 0 },
          { id: 3, value: 3 },
          { id: 4, value: 0 },
        ],
      };
      render() {
        return (
          <div>
            <Paper elevation={3} style={{padding: 20, margin:10,  }}>
            {  this.state.counters.map(counters => 
            <Counter key={counters.id} value={counters.value} /> ) }
            </Paper>
          </div>
        );
      }
    }
    
    export default Counters;

在我的 Counter 类中,我有 this.props.value 的逻辑和值

但是, value 属性是未定义的。在将其更改为 props.value 之前,这工作得很好

柜台类;

    import React, { Component } from "react";

class Counter extends Component {
  state = {
    value: this.props.value,
    tags: ["Tag1","Tag2"]
  }



 constructor() {
    super();
    this.handleIncrement = this.handleIncrement.bind(this);
    // handIncrement method needs to be binded to allow for 'this' keyword to have access to 
       it globally.
    //  You can also use the arrow function to bypass the super and binding methods.
  }

  renderTags() {
    if (this.state.tags.length === 0) return <p>There are no tags!</p>;

    return (
      <ul>
        {this.state.tags.map(tag => (
          <li key={tag}> {tag} </li>
        ))}
      </ul>
    );
    // Gives a key value to each element in the array. React needs to be able to access each element.
  }

  
  //   handleIncrement() {}
  handleIncrement = () => {
    let counterValue = this.props.value
    this.setState({ value: (counterValue += 1) });
    console.log("Clicked")
    console.log(counterValue)
    // In React you need to set the state to update the view(UI). You cannot do it direct i.e this.state.count += 1 as a direct method.
  };

  getBadgeClasses() {
    let classes = "badge m-2 badge-";
    classes += this.props.value === 0 ? "warning" : "primary";
    return classes;
  }
  formatCount() {
    return this.props.value === 0 ? "zero" : this.props.value;
  }

  render() {
    return (
      <div>
        {/* {this.state.tags.length === 0 && "Please create new tags"}
                {/* Render a conditional statement in line - A populated string in JS is 
                 considered truth y, so both values are true */}

        <span
          style={{ fontWeight: "bold", fontSize: 15 }}
          className={this.getBadgeClasses()}
        >
          {this.formatCount()}
        </span>

        <button
          onClick={this.handleIncrement}
          className="btn btn-secondary btn-sm"
        >
          Increment
        </button>

        {this.renderTags()}
      </div>
    );
  }
}

export default Counter;

我创建了一个新的 let 变量并将其设置为 props.value 的值,因为它是一个只读对象,但是我正在努力寻找原因。

认为这个 Counter 类中道具的引用是将逻辑转发给 Counters 类以进行四次渲染。

有任何想法吗?

标签: javascriptreactjsreact-props

解决方案


这个片段有一些错误:

  1. 如果你使用constructor你不应该)你需要用 props: 初始化实例super(props)
 constructor(props) {
    super(props);
    ...
  }
  1. 在类函数中使用this时,您必须将其绑定到类实例,或者只使用箭头函数(参见上面的链接):
// should be arrow function
getBadgeClasses = () => {}
formatCount = () => {}

推荐阅读