【发布时间】:2016-10-18 19:35:15
【问题描述】:
我很难理解为什么create-react-app 无法编译,告诉我error 'updateWord' is not defined no-undef。我对使用 ES6 进行 React 相当陌生。通常我会写一个像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>
);
}
}
【问题讨论】:
-
抱歉,仍有问题。我将方法更改为
updateWord,当我尝试以updateWord(input)调用该方法时,如果我尝试将其调用为this.updateWord(input),我仍然得到“错误'updateWord'未定义no-undef”,我得到错误“ App.js:55 Uncaught TypeError: this.updateWord is not a function" @AndrewLi 抱歉,我现在更新我的问题.... -
不,我认为双方都有误解 :( 我以为你的建议解决了我的问题,所以我跳了枪。重命名更新方法时我仍然有这个问题。@AndrewLi
-
没问题@AndrewLi
-
@AndrewLi 是的,我仍然得到“App.js:61 Uncaught TypeError: this.updateWord is not a function”
-
我想我明白了。使用
this.updateWord,然后将onInput更改为{this.handleInput.bind(this)}。
标签: javascript reactjs es6-class create-react-app