![](/img/trans.png)
[英]Best way to polyfill ES6 features in React app that uses create-react-app
[英]ES6 method is not defined in create-react-app
我很難理解為什么create-react-app
無法編譯,告訴我error 'updateWord' is not defined no-undef
。 我對使用 ES6 進行 React 相當陌生。 通常我會寫一個像const App = React.createClass({ });
這樣的組件const App = React.createClass({ });
但我決定嘗試一些語法糖。
我有父組件App
和子組件Input
:
class App extends Component {
constructor(props) {
super(props);
// all other code omitted...
}
handleInput(input) {
console.log(`handle: ${input}`);
updateWord(input);
// this also causes an error
// this.updateWord(input);
}
updateWord(input) {
console.log(`update ${input}`);
// why isn't this defined?
}
render() {
return (
<div className="App">
<Input onInput={this.handleInput} />
</div>
);
}
}
class Input extends Component {
handleInput(e) {
let input = e.target.value;
this.props.onInput(input);
}
render() {
return (
<form>
<input onChange={this.handleInput.bind(this)} />
</form>
);
}
}
我試過this.updateWord(input);
而不是updateWord(input)
但無濟於事。 我得到:
"App.js:55 Uncaught TypeError: this.updateWord is not a function"
通常,當我實現與我現在所做的類似的模式(使用 ES5)時,我沒有任何困難。 例如:
const App = React.createClass({
getInitialState: function() {
// all other code omitted...
},
handleInput: function(input) {
console.log(`handle: ${input}`);
this.updateWord(input);
},
updateWord: function(input) {
console.log(`update ${input}`);
// In theory, this implementation would not cause any errors?
},
render: function() {
return (
<div className="App">
<Input onInput={this.handleInput} />
</div>
);
}
}
問題是,當你做this.updateWord(...)
在this.handleInput
, this
指的是Input
組件。 讓我來說明這個問題:
當您設置onInput
處理程序時,如下所示:
onInput={this.handleInput}
在這里,由於您的Input
組件正在調用該函數, this
指的是Input
組件。 這是由於以下行:
this.props.onInput(input);
Input
組件正在調用handleInput
。 這意味着,在您的handleInput
函數中, this
上下文是Input
。 考慮這一行:
this.updateWord(input);
在handleInput
函數中。 在這里您調用this.updateWord
,但由於this
是Input
,它嘗試從不存在的Input
調用updateWord
,從而updateWord
錯誤。
解決方案是使用Function.prototype.bind
或箭頭函數將this
上下文顯式綁定為類( App
組件)而不是Input
組件。 從文檔:
bind()
方法創建一個新函數,當調用this
函數時,將其this
關鍵字設置為提供的值
您可以像這樣應用它:
onInput={this.handleInput.bind(this)}
或者更優選地在構造函數中:
this.handleInput = this.handleInput.bind(this);
使用第二個選項,您可以執行以下操作:
onInput={this.handleInput}
(這更可取,因為render
方法中的綁定將在每次render
時創建一個新函數,這不是首選)。
上一行中的this
上下文是類。 由於您綁定了this
,該類將被正確用作函數中的this
上下文,並且執行this.updateWord
將調用該類中的方法。
更可取的方法是使用箭頭函數而不是常規的 ES6 方法。 從文檔:
與函數表達式相比,箭頭函數表達式的語法更短,並且不綁定自己的
this
、arguments
、super
或new.target
。
我們可以通過將handleInput
分配給箭頭函數而不是常規方法來應用它:
handleInput = (input) => {
console.log(`handle: ${input}`);
this.updateWord(input);
}
這將完全消除bind
的使用,而是使用箭頭函數。 由於箭頭函數不綁定自己的this
,這意味着this
指的是封閉的上下文。 在上面的例子中,沒有使用方法,因此this
指的是類(封閉上下文)。 這將正確調用類方法updateWord
,因此,如果您走這條路線,則無需更改onInput
事件處理程序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.