首页 \ 问答 \ 使用作为prop传递给Child的函数更新父状态(Updating Parent state with function passed as prop to Child)

使用作为prop传递给Child的函数更新父状态(Updating Parent state with function passed as prop to Child)

一旦ChildForm调用作为道具传递的函数,我想刷新Parent组件的状态。 我的组件结构如下。

class Parent extends React.Component {
    constructor() {
        super();
        this.state = {data: []};
    }

    getThings() {
        //Working ajax get request for data
    }

    updateThing(obj){
        $.ajax({
          url: `/api/update/${obj.identifier}`,
          dataType: 'json',
          type: 'POST',
          data: obj,
          success: (res) => {
              this.getThings();
          },
          error: (xhr, status, err) => {
            console.error(`/api/update/${obj.identifier}`, status, err.toString());
          }
        });
    }

    componentDiMount() {
        this.getThings();
    }

    render() {
        let childForms = this.state.data.map((x, i) => {
            return (
                <ChildForm key={i} id={`thing${i}`} {...x} update={this.updateThing} />
            );
        });
        let dataVisuals = this.state.data.map((x, i) => {
            return (
                <DataViz key={i} {...x} />
            );
        });
        return (
            <div>
                {dataVisuals}
                {childForms}
            </div>
        );
    }
}

class ChildForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {...props};
        this.handleUpdate = this.handleUpdate.bind(this);
    }
    handleInputChange() {
        ///working input functionality to update form state
    }
    handleUpdate() {
        let obj = {...this.state};
        this.props.update(obj);
    }
    render() {
        //Form for updating individual thing
    }
}

当ChildForm调用this.props.update时,记录在数据库上成功更新,但出现this.getThings()不是函数并且Parent组件未更新的错误。 我如何触发Parent的状态更新?

编辑 :对不起,忘了表明,我有this.handleUpdate = this.handleUpdate.bind(this);ChildForm构造函数中。


I want to refresh the Parent Component's state once ChildForm invokes a function passed as a prop. My component is structured like below.

class Parent extends React.Component {
    constructor() {
        super();
        this.state = {data: []};
    }

    getThings() {
        //Working ajax get request for data
    }

    updateThing(obj){
        $.ajax({
          url: `/api/update/${obj.identifier}`,
          dataType: 'json',
          type: 'POST',
          data: obj,
          success: (res) => {
              this.getThings();
          },
          error: (xhr, status, err) => {
            console.error(`/api/update/${obj.identifier}`, status, err.toString());
          }
        });
    }

    componentDiMount() {
        this.getThings();
    }

    render() {
        let childForms = this.state.data.map((x, i) => {
            return (
                <ChildForm key={i} id={`thing${i}`} {...x} update={this.updateThing} />
            );
        });
        let dataVisuals = this.state.data.map((x, i) => {
            return (
                <DataViz key={i} {...x} />
            );
        });
        return (
            <div>
                {dataVisuals}
                {childForms}
            </div>
        );
    }
}

class ChildForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {...props};
        this.handleUpdate = this.handleUpdate.bind(this);
    }
    handleInputChange() {
        ///working input functionality to update form state
    }
    handleUpdate() {
        let obj = {...this.state};
        this.props.update(obj);
    }
    render() {
        //Form for updating individual thing
    }
}

When ChildForm invokes this.props.update, The record updates successfully on the db, but I get an error that this.getThings() is not a function and the Parent component is not updated. How can I trigger the state update on Parent?

EDIT: Sorry, forgot to show that I had this.handleUpdate = this.handleUpdate.bind(this); in ChildForm constructor.


原文:https://stackoverflow.com/questions/42327759
更新时间:2023-05-13 08:05

最满意答案

您可以在按钮图像中设置图像。 不会缩放,但您可以根据需要设置按钮。 在图像中看到我的按钮有100 * 100的图像和按钮比图像更大。

在这里输入图像描述


You can set Image in button Image. will not scale but you can set button as you want. See in the image my button have 100*100 image and button have more size than image.

enter image description here

相关问答

更多
  • 好的,所以你需要像这样在垂直模式下设置三个按钮。为此你可以使用raywenderlich这两个教程。 在第一篇教程中,他们将解释两种自动布局方法。 就像你需要的那样,他们用UIView来解释 教程1 教程2 阅读后确定你会确定你的应用程序的一些想法。 Ok so you need to set three button in vertical mode like this.For that you can make use this two tutorial by raywenderlich. In tha ...
  • 如果我没弄错的话, BitmapFactory自动将图像缩放到目标密度。 这就是为什么你得到的图像是640 x 400而不是预期的1280 x 800。 您最好使用BitmapFactory ,即指示它直接创建具有所需大小的图像。 这将更有效率,您的应用程序将不太可能遇到内存不足的问题。 看看这个答案 。 它显示了如何使用BitmapFactory选项。 更新: 要防止BitmapFactory进行默认缩放,您可以像这样更改原始代码。 代替: Bitmap bitmap= BitmapFactory.dec ...
  • 如果你真的想要放大图像,那么你可以在使用它之前调整它的大小。 在运行时调整其大小将只会失去CPU周期。 这是我用来缩放图像的类别: 的UIImage + Extra.h @interface UIImage (Extras) - (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize; @end; 的UIImage + Extra.m @implementation UIImage (Extras) - (UIImage *)im ...
  • 您可以在按钮图像中设置图像。 不会缩放,但您可以根据需要设置按钮。 在图像中看到我的按钮有100 * 100的图像和按钮比图像更大。 You can set Image in button Image. will not scale but you can set button as you want. See in the image my button have 100*100 image and button have more size than image.
  • UIView位于UIImageView的顶部 “坐在上面”是不够的。 使红色视图(UIView)成为地图视图(UIImageView)的子视图 。 滚动视图通过将缩放变换应用于地图视图来缩放地图视图,并且该缩放变换也将应用于地图视图的子视图。 the UIView sits on top of an UIImageView "Sit on top of" is not enough. Make the red view (the UIView) a subview of the map view (the ...
  • 对于遇到这个问题的任何人 - 我花了无数个小时试图找到一种方法来做到这一点,并最终得到屏幕的缩放因子(1为正常的Mac,2为视网膜)...代码看起来像这个: func getScaleFactor() -> CGFloat { return NSScreen.main()!.backingScaleFactor } 然后,一旦你有比例因子,你可以正常缩放视网膜的一半尺寸: if (scaleFactor == 2) { //halve size proportions for saving ...
  • 这个选择取决于你,但是如果你想要一个视图是可触摸的,那么UIButton就是你的选择。 此外, UIButton类包括按钮上所需的每个视觉效果(例如按下按钮)。 它还具有一些selected属性,可用于某些用途。 总之,如果您的视图的主要目标是可点击的,那么您应该使用UIButton 。 The choice is up to you but UIButton is made for if you want a view to be touchable. Moreover, the UIButton cla ...
  • 为什么不在xcode中添加你想要的按钮图像的图像视图,然后在它前面添加一个UI按钮并删除文本? 这不需要任何编程,并且耗时少且复杂。 Lucas, I followed your advice. I created a UIImageView and just added as a subview to the UIButton: // Delete key deleteKey.frame = CGRect(x: 719, y: 10, width: 134.0, height: 63.0) ...
  • 您需要计算单元格宽度。请尝试此代码。 class YourClass: UIViewController { //MARK:-Outlets @IBOutlet weak var yourCollectionView: UICollectionView! //Mark:-Variables var cellWidth:CGFloat = 0 var cellHeight:CGFloat = 0 var spac ...
  • 首先,您能否更清楚地提出问题? 我建议你想用矩形绘制你的图像而不想挤它,我是对的吗? 然后让我们试试这个方法: //The method: drawInRect:(CGRect) will scale your pic and squeeze it to fit the Rect area //So if you dont want to scale your pic, you can use the method below [image drawAsPatternInRect:(CGRect)_rect ...

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。