如何使用state更新按钮值属性中变量的值



我正在尝试写一个Figma插件,并使用React.js,这是我第一次尝试编码,我有很好的HTML/CSS知识,但js不那么多。

基本上,我希望newCornerRadius变量在被单击的按钮标记内的value属性内返回int。但现在我只得到第一个按钮的值,即使我点击了其他按钮,比如8、16、,。。。

Figma插件接口和检查员

这是我的ui.tsx代码

import * as React from 'react'
import * as ReactDOM from 'react-dom'
import './ui.css'
declare function require(path: string): any
class App extends React.Component {
cornerRadiusValues = [4, 8, 16, 24, 32, 40, 48];

cornerRadiusButtons = this.cornerRadiusValues.map((cornerRadiusValue, index) =>
<button key={index} value={cornerRadiusValue} id="cornerRadiusValue" onClick={() => this.setAttibute()}>{cornerRadiusValue}</button>
);
setAttibute = () => {
const newCornerRadius = parseInt((document.getElementById('cornerRadiusValue') as HTMLInputElement).value);
parent.postMessage({ pluginMessage: {type:'set-corner-radius-attribute',newCornerRadius}}, '*');
}
render() {
return <div>
{this.cornerRadiusButtons}
</div>
}
}
ReactDOM.render(<App />, document.getElementById('react-page'))

figma.showUI(__html__)
figma.ui.onmessage = msg => {
if (msg.type === 'set-corner-radius-attribute') {
for(const node of figma.currentPage.selection) {
if ("cornerRadius" in node) {
node.cornerRadius = msg.newCornerRadius;
} else {
console.log('corner radius not available')
}
}
}
}

我想我需要使用useState((,但我根本不知道在哪里以及如何使用!

提前感谢那些已经使用Stack Overflow近十年的人,我很高兴终于加入了它的JS部分

要访问按钮的值,可以将该值传递到onClick方法

import * as React from 'react'
import * as ReactDOM from 'react-dom'
import './ui.css'
declare function require(path: string): any
class App extends React.Component {
state={currentValue:''}
cornerRadiusValues = [4, 8, 16, 24, 32, 40, 48];

cornerRadiusButtons = this.cornerRadiusValues.map((cornerRadiusValue, index) =>
<button key={index} value={cornerRadiusValue} id="cornerRadiusValue" 
onClick={() => this.setAttibute(cornerRadiusValue)}>{cornerRadiusValue}</button>
);
setAttibute = (value) => {
this.setState({
...this.state,
currentValue:value
})
}
render() {
return <div>
{this.cornerRadiusButtons}
</div>
}
}
ReactDOM.render(<App />, document.getElementById('react-page'))

,您可以使用此命令this.state.currentValue访问组件内部的状态值

将一个对象复制到另一个

var firstObject = {
key1 : 'value1',
key2 : 'value2'
};
var secondObject = {
...firstObject,
key3 : 'value3',
key4 : 'value4'
};

最新更新