我试图编写一个Figma插件并使用React.js,这是我第一次尝试编写代码,我有很好的HTML/CSS知识,但是JS没有那么多。
基本上,我希望newCornerRadius变量返回正在单击的按钮标记内的value属性内的int。但是现在我只得到第一个按钮的值,即使我点击其他按钮,比如8,16,…
这是我的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(),但我只是不知道在哪里和如何使用!
谢谢各位,我已经使用堆栈溢出了近十年了,我很高兴终于加入了JS的一部分。
发布于 2022-03-12 18:10:47
要访问按钮的值,可以将该值传递给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'
};
https://stackoverflow.com/questions/71452014
复制相似问题