【发布时间】:2021-01-20 09:44:31
【问题描述】:
我有一个 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 类中 props 的引用是将逻辑转发给 Counters 类进行四次渲染。
有什么想法吗?
【问题讨论】:
-
请关注问题,您在其他平台上的挣扎故事/糟糕的措辞是不必要的(问题已编辑)。
标签: javascript reactjs react-props