所以我正在學習關于 React 的課程,但我不知道如何解決這個問題。它建議我將Spread運算子'...'而不是'this'。從陣列中選擇元素。但是當我這樣做時,它仍然顯示錯誤“狀態”未定義為非未定義。我是 React 的新手,所以我在這里做錯了什么嗎?
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
import { render } from '@testing-library/react';
import React from 'react';
import { Component } from 'react/cjs/react.production.min';
import './App.css';
import Person from './Person/Person';
class App extends Component {
state = {
persons: [{name: 'Max', age: 22},
{name: 'Manu', age: 19},
{name: 'Stephanie', age: 41},
{name: 'George', age: 40}
]
}
render() {
return (
<div className="App">
<h1>Hi, I am a React App</h1>
<p>This is really working!</p>
<button>Switch Name</button>
<Person name= {this.state.persons[0].name} {this.state.persons[0].age}/>
<Person {this.persons[1].name} {this.state.persons[1].age}/>
<Person {this.state.persons[2].name} {this.state.persons[2].age}> My Hobbie is swimming.</Person>
<Person {this.state.persons[3].name} {this.state.persons[3].age}/>
</div>
);
}
}
export default App;
uj5u.com熱心網友回復:
假設<Person />組件接受age和name屬性,您可以使用擴展語法將具有匹配屬性的整個物件傳播到該組件,如下所示:
<Person {...{this.persons[0]}} />
以上是等效的但簡寫
<Person name={this.persons[0].name} age={this.persons[0].age} />
另請注意您插入的錯誤語法:
<Person name= {this.state.persons[0].name} {this.state.persons[0].age}/>
首先,空格不應該存在,因為您需要將值傳遞給給定的屬性,這與普通 JS 語法不同,您可以在其中創建帶有或不帶空格的變數:
const x = 1; 或者 const x=1;
其次,您試圖將age值傳遞給組件,但您還沒有指出它應該分配給哪個屬性。
繼續加油,祝你好運。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/394563.html
標籤:javascript html 反应 jsx
上一篇:單擊所有div后,如何更改CSS
下一篇:@之后的電子郵件域的正則運算式
