[英]How can I change a prop on a React Element saved in an Array? JSX
Im creating this custon React Element and pushing it into an array.我创建了这个自定义 React Element 并将其推送到一个数组中。
let new_image = <KonvaImage
ref={newImageRef}
key={this.state.itemArray.length}
image={image}
width={new_size.width * reduction}
height={new_size.height * reduction}
x={ (width / 2 ) - (new_size.width * reduction / 2)}
y={ (height / 2) - (new_size.height * reduction / 2)}
draggable
/>
this.state.itemArray.push(new_image)
But I want to make the prop "draggable" conditional, depending on one state variable from his parent.但我想让道具“可拖动”有条件,这取决于他父母的一个 state 变量。
But it seems that i can't because this react element is read-only when it's created on the code above.但似乎我不能,因为这个反应元素在上面的代码上创建时是只读的。
I want to change the prop on render, here:我想改变渲染的道具,在这里:
render(){
return(
{ //Renders all items into the canvas
this.state.itemArray.map(item => (
item
))
}
)
}
I have no clue on what to do, please help!我不知道该怎么做,请帮忙!
You could consider pushing a higher-order component to the array and then providing the prop when you render it.您可以考虑将高阶组件推送到数组,然后在渲染时提供道具。
You would add it like this:您可以像这样添加它:
let new_image = ({ draggable }) => (
<KonvaImage
ref={newImageRef}
key={this.state.itemArray.length}
image={image}
width={new_size.width * reduction}
height={new_size.height * reduction}
x={width / 2 - (new_size.width * reduction) / 2}
y={height / 2 - (new_size.height * reduction) / 2}
draggable={draggable}
/>
);
this.state.itemArray.push(new_image)
And then when iterating through the array:然后在遍历数组时:
render(){
return this.state.itemArray.map((Item) => <Item draggable={false} />);
};
React.cloneElement(
element,
[props],
[...children]
)
You should be able to do this:你应该能够做到这一点:
this.state.itemArray.push(React.cloneElement(
new_image,
{ draggable: whatever_you_want }
))
If you prefer to do this to the whole array later, and if your set of components is a genuine Array, you can use traditional array addressing and manipulation to modify one or more items by replacing the initial components with clones whose properties have been modified.如果您希望稍后对整个数组执行此操作,并且如果您的组件集是真正的数组,则可以使用传统的数组寻址和操作来修改一个或多个项目,方法是用属性已修改的克隆替换初始组件。 Otherwise, you'll need
React.Children
to work with a collection of children.否则,您将需要
React.Children
来处理一组孩子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.