组件级 onChange 事件?

Noi*_*art 3 reactjs

我有一个选项页面组件。该组件由行组成。每一行都是一个设置。该设置是选择、检查、单选或自定义元素。此组件以两种方式更新:

  1. AJAX 告诉它使用 setState 进行更新 - 我将这个 setState 分类为组件 onChange 而不是组件更新
  2. 用户操作一行,触发select/radio/check onChange触发,onChange触发最上面组件的setState——这个setState我归类为组件onChange

当#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)