【发布时间】:2020-03-04 17:46:56
【问题描述】:
简单地说,我想构建一个界面,用户可以通过该界面将对象插入到 div 中。
用户应该能够选择放置的对象并更改它们的设置(颜色、大小、旋转......)。
我刚开始做出反应并将我的想法付诸实践。
class Elements extends React.Component {
constructor(props) {
super(props);
this.displayData = [];
this.state = {
showdata: this.displayData,
elementData: {
color: "red",
}
};
this.addDiv = this.addDiv.bind(this);
this.switchColor = this.switchColor.bind(this);
this.giveConsoleData = this.giveConsoleData.bind(this);
};
giveConsoleData(){
console.log(this.state);
}
switchColor() {
if(this.state.elementData.color == "red"){
this.setState({
showdata: this.displayData,
elementData: {
color: "blue",
}
});
}else if(this.state.elementData.color == "blue"){
this.setState({
showdata: this.displayData,
elementData: {
color: "red",
}
});
}
}
addDiv() {
this.displayData.push(<div style={this.state.elementData} ><FaArrowUp size={32} /></div>);
this.setState({
showdata : this.displayData
});
}
render() {
const items = this.state.showdata.map(i => <li>{i}</li>);
return (
<div>
<Button type="submit" block variant="primary" onClick={this.addDiv}>Primary</Button>< br/>
<Button type="submit" block variant="primary" onClick={this.switchColor}>ChangeColor</Button>< br/>
<Button type="submit" block variant="primary" onClick={this.giveConsoleData}>Consolenlog</Button>< br/>
{items}
<div style={this.state.elementData}><h1>I Can Change</h1></div>
</div>
);
}
}
export default Elements;
我现在的问题是 h1 标题可以改变颜色,但已经放置的对象不能。
我的方法完全错误吗?
是不是当你推送 div 元素时保存的是当前颜色值而不是状态中的颜色元素?
【问题讨论】:
-
嗨@christopherGhl,你能提供一些虚拟数据的现场工作小提琴示例吗?
-
它认为你的怀疑是对的。我会将
this.state.elementData传递给render()中的组件,而不是addDiv() -
我也不建议将 React 组件存储在数组中。我会将数据存储在数组中,然后在您的渲染函数中,根据数据决定要渲染的内容。对于您当前的示例,您的
displayData唯一需要跟踪的是要渲染的项目数量。然后在render中你可以简单地渲染那么多<div style={this.state.elementData} ><FaArrowUp size={32} /></div>s
标签: javascript reactjs state react-props react-state