【发布时间】:2020-03-12 13:43:35
【问题描述】:
当使用 toggleSelected () 在另一个组件中单击选项时,我正在尝试更新我的应用程序状态中的选项数组中的样式对象。有谁知道如何最好地访问对象并将背景颜色设置为不同的颜色?
App.js
this.state = {
options: [
{
id: 0,
label: "Industrial Truck and Tractor Operators",
value: "53-7051",
style: {
display: "flex",
margin: "auto",
paddingTop: "1em",
paddingBottom: "1em",
paddingLeft: "1em",
borderBottom: "solid",
borderColor: "black",
borderWidth: ".1em",
color: "#64bd9a",
backgroundColor: "white"
},
tooltip_text:
'Operate industrial trucks or tractors equipped to move materials around a warehouse, storage yard, factory, construction site, or similar location. Excludes “Logging Equipment Operators" (45-4022).'
},
{
id: 1,
label: "Order Clerks",
value: "43-4151",
style: {
display: "flex",
margin: "auto",
paddingTop: "1em",
paddingBottom: "1em",
paddingLeft: "1em",
borderBottom: "solid",
borderColor: "black",
borderWidth: ".1em",
color: "#64bd9a",
backgroundColor: "white"
},
tooltip_text:
'Receive and process incoming orders for materials, merchandise, classified ads, or services such as repairs, installations, or rental of facilities. Generally receives orders via mail, phone, fax, or other electronic means. Duties include informing customers of receipt, prices, shipping dates, and delays; preparing contracts; and handling complaints. Excludes "Dispatchers, Except Police, Fire, and Ambulance" (43-5032) who both dispatch and take orders for services.'
}
],
value: null,
styles: {
//container style is working
marginTop: "2em",
marginLeft: "2em",
borderStyle: "solid",
borderWidth: ".1em",
borderBottom: "none",
borderRight: "solid",
width: "19em",
textAlign: "justify",
backgroundColor: "white",
boxShadow: "3px 6px 5px #9E9E9E"
},
className: "",
selectedClassName: "",
loading_State: true, //this changes to false when the component loads
childrenCount: 0
};
toggleSelected = child => {
this.setProps({options.indexOf('1').style.backgroundColor: "gray" })
};
组件.js
render() {
return (
<div style={this.props.styles}>
{this.props.options.map(option => (
<div
key={option}
id={"option" + option.id}
style={option.style}
onClick={e => {
if (this.props.setProps) {
this.props.setProps({ value: e.target.value });
} else {
this.setState({ value: e.target.value });
}
this.props.toggleSelected(option.id); //passing my index here to the function
}}
>
<span id={option.id}> {option.label} </span>
<UncontrolledTooltip
placement="right"
target={"option" + option.id}
>
{option.tooltip_text}
</UncontrolledTooltip>
</div>
))}
</div>
);
}
在此处更新样式对象方面,我是否以正确的方式进行此操作。我应该使用不同的方法。我也想在不使用 CSS 的情况下执行此操作,因此添加 classNames 不是我想要做的。
【问题讨论】:
-
setProps是做什么的。我认为您可能需要重新考虑应用程序流程。实现一件相当简单的事情有点复杂。