React子组件回调问题:如何在触发父组件回调前执行preupdate?
解决React子组件先执行自身方法再触发父组件回调的问题
Hey there! Let's work through this together. First, let's spot a couple of small issues in your original code that would break it before we even get to your main question:
- The
rendermethods in both components aren't returning the JSX elements (React requires render to return a valid element) - You passed the prop as
callBackfrom the parent, but tried to access it ascallbackin the child (case sensitivity matters here!)
Now, to achieve your goal—calling the child's preupdate function first before triggering the parent's callback—we just need to create a custom click handler in the child component. This handler will first run preupdate, then invoke the parent's callback.
Here's the fixed and updated code:
var ParentComponent = React.createClass({ update: function() { console.log("updated!"); }, render: function() { // Add return to render the child component return <ChildComponent callBack={this.update} /> } }) var ChildComponent = React.createClass({ preupdate: function() { console.log("pre update done!"); }, // Custom click handler to sequence the calls handleButtonClick: function() { // 1. First run the child's own preupdate method this.preupdate(); // 2. Then trigger the parent's callback this.props.callBack(); }, render: function() { // Bind our custom handler instead of directly calling the parent's callback return <button onClick={this.handleButtonClick}>click to update parent</button> } })
How this works:
- When the button is clicked, it triggers
handleButtonClickin the child - This function first executes
this.preupdate()to log "pre update done!" - Then it calls
this.props.callBack()which invokes the parent'supdatemethod, logging "updated!"
You'll see the console output in the order you want: first "pre update done!", then "updated!".
内容的提问来源于stack exchange,提问作者Peekay
相关产品推荐
相关产品推荐

