【问题标题】:Component level onChange event?组件级别的 onChange 事件?
【发布时间】:2016-01-01 08:51:11
【问题描述】:

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

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

当 #2 发生时,意味着用户操作的组件,我希望最顶层组件上的 onChange 触发。有这样的活动吗?我似乎在组件生命周期中找不到它。

我不能使用componentDidUpdate 的原因是当用户触发onChange of row 时,我需要使用新信息向服务器发出请求。如果 AJAX 告诉组件更新,onComponentDidUpdate 将触发,但我不需要发出 AJAX 请求。

【问题讨论】:

  • 不知道你到底想要什么。不能将 onChange 从父组件传递到带有道具的行来解决您的问题吗?请问the onChange on the top most component to fire是什么意思?你的意思是事件委托?
  • 感谢@ZhangChao 的快速回复。基本上,我想知道在最顶层组件上触发的componentDidUpdate 是由于用户操纵的 setState 还是来自 AJAX setState。
  • 当用户操作导致onChange,你想触发setState然后在componentDidUpdate发出请求,对吗?为什么不在onChange 中提出这个请求,并在得到这个请求的响应时触发setState?我认为这是做这些事情的一种更常见的方式,并且您不必在componentDidUpdate中区分ajax方式和用户方式。
  • 我对使用 onChange 犹豫不决,因为如果它在实际上没有任何改变的情况下触发了怎么办。但我认为 react 使 onChange 的工作方式不同,因为它不会触发,除非它真的被改变了,这是真的吗?谢谢@ZhangChao!

标签: reactjs


【解决方案1】:

您可以通过在其子组件属性上从顶级组件传递一个回调来做到这一点。然后,子组件 onChange 事件将使用 this.props.callbackName() 调用回调。例如

TopComponent.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}) />
     }
 }

ChildComponent.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}/>)
  }
}

【讨论】:

  • 啊,这真是个好主意,非常感谢!我也从这个帖子中学习了一些es2015,谢谢!
  • 是否可以将回调函数命名为onPropertyChangeonChange?我想,为了保持一致性,但是,我会压倒一些重要的事情吗?谢谢
  • 如果我们想在回调中将事件作为参数传递,以便我们可以访问 event.target.value 中的值?
猜你喜欢
  • 2017-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-05
  • 2014-09-23
  • 2021-04-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多