在youtube上关注此示例:
https://www.youtube.com/watch?v=NoaxsCi13yQ#t=17m12s
我尝试输入更改宽度'在州,然后看到div改变了。这是我的代码:
import React, { Component } from 'react';
export default class TestColors extends Component {
constructor(props){
super(props);
this.handleInputChange = this.handleInputChange.bind(this);
this.state = {
width: 300,
};
}
handleInputChange(event) {
this.setState((prevState, props) => ({
width: event.target.value,
}));
}
render() {
const style = {
backgroundColor: 'orange',
width: this.state.width,
};
return (
<div style={style}>
<input onChange="this.handleInputChange"/> {this.state.width}
</div>
);
}
}
但是我在渲染上得到了这个错误:
warning.js:35 Warning: Failed form propType: Invalid prop `onChange` of type `string` supplied to `input`, expected `function`. Check the render method of `TestColors`
当我更改输入值时,我收到此错误:
LinkedValueUtils.js:132 Uncaught TypeError: inputProps.onChange.call is not a function
at Object.executeOnChange (LinkedValueUtils.js:132)
at ReactDOMComponent._handleChange (ReactDOMInput.js:241)
at Object.ReactErrorUtils.invokeGuardedCallback (ReactErrorUtils.js:69)
at executeDispatch (EventPluginUtils.js:85)
at Object.executeDispatchesInOrder (EventPluginUtils.js:108)
at executeDispatchesAndRelease (EventPluginHub.js:43)
at executeDispatchesAndReleaseTopLevel (EventPluginHub.js:54)
at Array.forEach (<anonymous>)
at forEachAccumulated (forEachAccumulated.js:24)
at Object.processEventQueue (EventPluginHub.js:254)
我不知道为什么网站上的一些例子使用(没有prevState):
handleInputChange(event) {
this.setState( {
width: event.target.value,
});
}
而不是:
handleInputChange(event) {
this.setState((prevState, props) => ({
width: event.target.value,
}));
}
有区别吗?为什么输入没有用值和宽度更新标签,我需要还原剂?
阅读此链接后,我开始认为setState是反应周期更新中存在很多问题的恶魔:
https://medium.com/javascript-scene/setstate-gate-abc10a9b2d82
但是我没有在互联网,博客等上找到明确的答复,任何人都可能是理解这个问题的关键吗?
答案 0 :(得分:0)
因为在onClick中你想要调用javaScript函数,你需要在{}
而不是""
中包装函数调用,因为函数是javascript,而在jsx中我们将javascript包装在{}
里面所以在你的jsx做一个改变:
<input onChange={this.handleInputChange}/>
实际发生的是它期待一个函数并且你提供了一个字符串,所以给出了一个错误。
编辑:正如您提到的使用setState函数的不同方式,语法错误。而是像以下一样使用它:
handleInputChange(event) {
this.setState((prevState, props) => {
width: event.target.value,
});
}