Update a specific property of an object attribute in a Wordpress Gutenberg block

不想你离开。 提交于 2021-01-28 02:07:58

问题


I have a custom Gutenberg block with an attribute:

valuesObj: {
    type: 'object',
    default: {},
}

I want to update a specific property within that object when an input is changed. So I have created a function that gets called from onChange on the component:

<TextInput
    value={ valuesObj[index] }
    onChange={ (value) => this.onChangeValue(value, index) }
/>

This is the function that gets called:

onChangeValue(value, index) {
    var newValuesObj = this.props.attributes.valuesObj;

    newValuesObj[index] = value;

    this.props.setAttributes({ valuesObj: newValuesObj });
};

For some reason this doesn't seem to work at all. When I type in the TextInput nothing changes. When I save the post, nothing is saved for that attribute. I know the function is being called correctly and is passing the correct value and index (I console.log them). I've been scouring the Gutenberg documentation, but it doesn't seem to mention anything about this.

Not sure what I am missing/doing wrong.


回答1:


You're calling onChangeURL , but your method is called onChangeValue.

I'm not sure where the value of index is coming from but try to create a new object in your onChangeValue and set this new object for your attribute.

Try changing your onChangeValue to something like:

onChangeValue(value, index) {
    var newValuesObj = {};
    newValuesObj[index] = value;
    this.props.setAttributes({ valuesObj: newValuesObj });
  }


来源:https://stackoverflow.com/questions/56452438/update-a-specific-property-of-an-object-attribute-in-a-wordpress-gutenberg-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!