React set state property dynamically

淺唱寂寞╮ 提交于 2019-12-11 01:13:29

问题


I'm using react and I have some methods to set the state of my COmponent separately. I have the following methods:

setLineColor(value){
  this.setState({stroke:value},()=>{
  this.props.data(this.getStyleData());
 });
}
setFillColor(value){
 this.setState({ fill:value},()=>{
 this.props.data(this.getStyleData());
 });
}
setMode(value){
 this.setState({ mode:value},()=>{
 this.props.data(this.getStyleData());
 });
}

How can I combine the methods, so that I can have something like:

setAttribute(propery,value){...}

?


回答1:


Like this

setAttribute(property, value) { 
  this.setState({ [property]: value }, () => {
    this.props.data(this.getStyleData());
  });
}

Example



来源:https://stackoverflow.com/questions/37591430/react-set-state-property-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!