问题
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