我有這兩個關于 JS 的問題。我必須說我真的做了我的研究,但找不到任何關于它們的資訊。
問題是:
- 為什么不能在類內部、函式/方法外部使用
console.log和變數識別符號(var、、、let) ? 例如(偽代碼):const
class App extends Component {
console.log(this) <--* ['Unexpected keyword or identifier']
let a = 1 <--* ['Unexpected token']
state = { <--* [variable without identifier is alright]
characters: [
{
name: 'Charlie',
job: 'Janitor'
}, etc...
}
removeCharacter = (index) => {
console.log(this) <--* [works here normally]
const characters = this.state.characters
etc...
})
})
...
}
- 為什么一個函式需要呼叫另一個函式?我的意思是,在什么情況下它變得必要?這來自類似的東西:
const TableBody = (props) => {
const rows = props.characterData.map((row, index) => {
return (
<tr key={index}>
<td>{row.name}</td>
<td>{row.job}</td>
[this] *--> <button onClick={() => props.removeCharacter(index)}>Delete</button>
</tr>
)
[instead of something like] *--> <button onClick={props.removeCharacter(index)}>Delete</button>
我的意思是,props.removeCharacter(index)它本身已經是一個電話,不是嗎?
謝謝!
uj5u.com熱心網友回復:
你可以做
class TheClass {
theProperty = 'theValue'
作為類欄位語法的一部分,它是語法糖
class TheClass {
constructor() {
this.theProperty = 'theValue'
它僅用于將屬性分配給實體,僅此而已。
console.log(this)不起作用,因為它在那里沒有意義 - 它沒有分配屬性,它只是一個浮動運算式。
let a = 1不起作用,因為你不能在那里宣告一個新變數 -{一個類不會創建一個新塊。使用類欄位分配給實體的屬性,并且不會創建新的獨立識別符號。
為什么一個函式需要呼叫另一個函式?
在這種情況下,它是必需的,因為您需要傳遞一個引數。如果removeCharacter不接受爭論,你可以做
<button onClick={props.removeCharacter}>
但它確實接受一個引數,該引數應該是索引。但是傳遞給點擊處理程式的默認引數是event。
你不能做
onClick={props.removeCharacter(index)}
因為那會removeCharacter立即呼叫。它相當于
const result = props.removeCharacter(index);
// ...
<button onClick={result}
這不是所需的邏輯 - 您希望removeCharacter在單擊按鈕時呼叫,而不是在創建按鈕時呼叫。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/438545.html
標籤:javascript 反应 功能 班级 标识符
上一篇:如何計算熊貓分類列的變化
下一篇:看不懂Python的兩行代碼
