gio*_*gim 19 javascript reactjs
想象一下这个(简化的)某个父组件的函数成员:
handleInputChange(e) {
// let val = e.target.value; - if I uncomment this, it works.
// Update text box value
this.setState(function (prevState, props) {
return {
searchValue: e.target.value,
}
})
}
Run Code Online (Sandbox Code Playgroud)
和textbox(子组件的成员)如下:
<input type="text" onChange={that.props.handleInputChange} value={that.props.searchValue} />
Run Code Online (Sandbox Code Playgroud)
当我在文本字段中输入内容时,我得到错误handleInputChange.
如果我取消注释props函数内的第一行,我将文本框值存储在Cannot read property 'value' of null变量中,它运行良好.想法为什么?
PS.如上所述,该handleInputChange函数在父组件中声明,而实际输入控件在子组件中定义.您可以看到我如何使用click处理程序和值作为子组件中的props.
Prz*_*ski 30
这是因为React正在进行事件轮询 - 所有事件的字段在回调完成后都会变为空,因此您在异步setState回调中将它们视为空值.
请将您的事件数据复制到变量或调用event.persist()以禁用此行为.
handleInputChange(e) {
e.persist();
this.setState(function (prevState, props) {
return {
searchValue: e.target.value,
}
})
}
Run Code Online (Sandbox Code Playgroud)
要么:
handleInputChange(e) {
const val = e.target.value;
this.setState(function (prevState, props) {
return {
searchValue: val
}
})
}
Run Code Online (Sandbox Code Playgroud)
请参阅以下示例:
class Example extends React.Component {
constructor() {
super()
this.state = { }
}
handleInputChangeCopy = (e) => {
const val = e.target.value;
console.log('in callback');
console.log(e.target.value);
this.setState(function (prevState, props) {
console.log('in async callback');
console.log(val);
return {
searchValue: val
}
})
}
handleInputChangePersist = (e) => {
e.persist();
console.log('in callback');
console.log(e.target.value);
this.setState(function (prevState, props) {
console.log('in async callback');
console.log({ isNull: e.target === null })
console.log(e.target.value);
return {
searchValue: e.target.value
}
})
}
handleInputChange = (e) => {
console.log('in callback');
console.log(e.target.value);
this.setState(function (prevState, props) {
console.log('in async callback');
console.log({ isNull: e.target === null })
console.log({ event: e });
console.log(e.target.value);
return {
searchValue: e.target.value
}
})
}
render() {
return (
<div>
<div>Copy example</div>
<input
type="text"
onChange={this.handleInputChangeCopy}
/>
<p>Persist example</p>
<input
type="text"
onChange={this.handleInputChangePersist}
/>
<p>Original example - please note nullified fields of the event in the async callback. <small>Breaks the example, please re-run after a Script error</small></p>
<input
type="text"
onChange={this.handleInputChange}
/>
<div style={{height: 300}} />
</div>
)
}
}
ReactDOM.render(
<Example searchValue={"test"} />,
document.getElementById('app')
)Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>Run Code Online (Sandbox Code Playgroud)