带有属性作为参数传递的Wordpress Gutenberg SetAttributes

时间:2019-08-31 10:17:49

标签: reactjs wordpress-gutenberg

我正在创建具有许多属性的Gutenberg块,并尝试为可通过输入字段更改的属性创建通用函数。对于属性title,我具有:

<RichText
  onChange={this.props.onTitleChange}
  value={this.props.title}
/>

function onTitleChange(value) {
  setAttributes({title: value});
}

这有效。现在,尽管我希望创建一个泛型函数,其中setAttributes() title可以是我从React onChange传递的任何函数。我尝试了另一个功能onValueChange

<RichText
  onChange={this.props.onValueChange.bind("title")}
  value={this.props.title}
/>

function onValueChange(value) {
  setAttributes({this: value});
}

这不起作用,因为“ this”不是我的区块的属性。即使我的函数this中的onValueChange等于“ title”,也随bind()函数一起传递。 我不确定我尝试做的事情是否可行,因为我不完全了解setAttributes()函数,但是如果可以做到,它将节省大量时间和额外的代码,因为否则我会必须为我的所有属性创建一个onXChange()函数。所以我的问题是:如何使用setAttributes()在动态属性上设置值?

2 个答案:

答案 0 :(得分:1)

原来,我要做的就是将this用括号括起来,所以:

function onValueChange(value) {
  setAttributes({[this]: value});
}

保留bound属性:

onChange={onValueChange.bind('title')}

另一种选择是像这样使用setAttributes内联:

onChange={ title => setAttributes( { title } ) }

确保将title更改为属性名称。

答案 1 :(得分:0)

目前我能想到这个:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    // create a ref to store the textInput DOM element
    this.textInput = React.createRef();
  }

  render() {
    // tell React that we want to associate the ref
    // with the `textInput` that we created in the constructor
    <RichText
      onChange={ ()=> this.props.onValueChange("title",value) }
      value={this.props.title}
      ref={this.textInput}
    />
  }
}


  function onValueChange(property ,value) {
    let element = ReactDOM.findDOMNode(this.refs.textInput);
    element.setAttributes({property: value});
  }

PS: Not Sure wheather this is going to work but yeah you can give a try.