我有一个选项页面组件。该组件由行组成。每一行都是一个设置。该设置是选择、检查、单选或自定义元素。此组件以两种方式更新:
当#2 发生时,意味着用户操作的组件,我希望最顶部组件上的 onChange 被触发。有这样的活动吗?我似乎无法在组件生命周期中找到它。
我不能使用的原因componentDidUpdate是因为当用户触发行的 onChange 时,我需要使用新信息向服务器发出请求。如果 AJAX 告诉组件更新, onComponentDidUpdate 将触发,但我不需要发出 AJAX 请求。
小智 5
您可以通过在其子组件属性上传递来自 Top Component 的回调来实现。然后将通过使用 this.props.callbackName() 由子组件 onChange 事件调用回调。例如
顶部组件.js
// import react (i'm using es2015)
// but the concept is the same whether you use it or not
import React, {Component} from 'react'
class TopComponent extends Component {
// the callback
onChildComponentChange(){
doAjax().then(function(data){
this.setState({foo: data})
})
}
render(){
return (<ChildComponent onPropertyChange={this.onChildComponentChange}) />
}
}
Run Code Online (Sandbox Code Playgroud)
子组件.js
import React, {Component} from 'react'
class ChildComponent extends Component {
onChangeHandler(){
// from this handler we call the top component callback
this.props.onPropertyChange(data) // the name of props we pass from top component
}
render(){
return (<RowComponent onClick={this.onChangeHandler}/>)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4039 次 |
| 最近记录: |