反应本机setState数组

时间:2019-01-16 08:25:38

标签: arrays reactjs setstate

我需要更改数组元素的状态。这种改变导致视图和图像的颜色改变。 如何在react native中更改状态并上传更改?

1 个答案:

答案 0 :(得分:0)

如果您要更改应用程序的主题(具有静态颜色和图像URL),最好在CSS中进行处理,并以状态保存主题名称,如下所示:

class App extends React.Component {
  state = {
    theme: 'green-theme'
  }
  
  handleClick = () => {
    this.setState({ theme: 'red-theme' })
  }
  
  render(){
    const { theme } = this.state;
    return (
      <button className={theme} onClick={this.handleClick}>change theme</button>
    )
  }
}

ReactDOM.render(<App />, document.getElementById('root'))
.green-theme {
  background-color: lightgreen;
  /* background-image: url('path/to/img1'); */
}

.red-theme {
  background-color: lightcoral;
  /* background-image: url('path/to/img2'); */
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>