gpt4 book ai didi

javascript - 如何将事件传递给 setState 回调函数?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:39:42 26 4
gpt4 key购买 nike

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
}
);
}

关于javascript - 如何将事件传递给 setState 回调函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50826078/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com