在React中是否可以将外部事件传递给setState的回调函数?
例
someFunc(event) {
this.setState(
{
value: event.target.value
},
() => {
this.props.onChange(event); // <- cannot pass to here
}
);
}
编辑:请参阅Liam的下面接受的解决方案,以获得优秀的答案,
以下是我的问题的具体解决方案:
解
someFunc(event) {
event.persist() // <- add this line and event should pass without a problem
this.setState(
{
value: event.target.value
},
() => {
this.props.onChange(event);
}
);
}
解决方法:
您需要提取值或使用e.persist()
https://reactjs.org/docs/events.html#event-pooling
class App extends React.Component {
something = (value) =>{
{console.log(value, 'coming from child')}
}
render() {
return (
<div >
<Hello text={this.something} />
</div>
);
}
}
class Hello extends React.Component {
constructor() {
super()
this.state = {
value: ''
}
}
onChange = (e) => {
const value = e.target.value;
this.setState({ value }, () => {
this.props.text(value)
})
}
render() {
return (
<div style={{ padding: 24 }}>
<input onChange={this.onChange} value={this.state.value} />
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
<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='root' ></div>
或者如果你打算传递值状态,你可以在回调中使用this.state.value它将起作用.
someFunc(event) {
this.setState(
{
value: event.target.value
},
() => {
this.props.onChange(this.state.value); // <- this should work
}
);
}