Reactjs Wordpress Gutenberg SetAttributes,属性作为参数传递
我正在创建一个具有许多属性的Gutenberg块,并尝试为可以使用输入字段更改的属性创建一个通用函数。对于属性Reactjs Wordpress Gutenberg SetAttributes,属性作为参数传递,reactjs,wordpress-gutenberg,Reactjs,Wordpress Gutenberg,我正在创建一个具有许多属性的Gutenberg块,并尝试为可以使用输入字段更改的属性创建一个通用函数。对于属性标题,我有: <RichText onChange={this.props.onTitleChange} value={this.props.title} /> 这很有效。现在,尽管我希望创建一个通用函数,其中setAttributes()title可以是我从ReactonChange传递的任何内容。我尝试了另一个函数onValueChange: <RichT
标题
,我有:
<RichText
onChange={this.props.onTitleChange}
value={this.props.title}
/>
这很有效。现在,尽管我希望创建一个通用函数,其中setAttributes()
title
可以是我从ReactonChange
传递的任何内容。我尝试了另一个函数onValueChange
:
<RichText
onChange={this.props.onValueChange.bind("title")}
value={this.props.title}
/>
这不起作用,因为“This”不是我的块的属性。即使我的函数onValueChange
中的this
与bind()
函数传递的“title”相等。
我不确定我试图做的是否可行,因为我不完全理解
setAttributes()
函数,但如果可以做到,它将节省大量时间和额外的代码,因为否则我将不得不为所有属性创建onXChange()
函数。所以我的问题是:如何使用setAttributes()
在动态属性上设置值 目前我可以想到:
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});
}
类MyComponent扩展了React.Component{
建造师(道具){
超级(道具);
//创建一个ref来存储textInput DOM元素
this.textInput=React.createRef();
}
render(){
//告诉React我们要关联ref
//使用我们在构造函数中创建的“textInput”
this.props.onValueChange(“title”,value)}
值={this.props.title}
ref={this.textInput}
/>
}
}
函数onValueChange(属性、值){
let element=ReactDOM.findDOMNode(this.refs.textInput);
setAttributes({property:value});
}
PS:不确定这是否有效,但是的,你可以试试。
事实证明,我所要做的就是将这个
括在括号中,所以:
function onValueChange(value) {
setAttributes({[this]: value});
}
保留绑定属性:
onChange={onValueChange.bind('title')}
另一个选项是使用setAttributes
inline,如下所示:
onChange={ title => setAttributes( { title } ) }
确保将title
更改为属性的名称
onChange={onValueChange.bind('title')}
onChange={ title => setAttributes( { title } ) }