Deprecation warning using this.refs

后端 未结 3 1601
忘了有多久
忘了有多久 2020-11-27 06:16

I have a React component and I want to toggle a css class when clicked.

So I have this:

export class myComponent extends React.Component {
  construc         


        
3条回答
  •  孤城傲影
    2020-11-27 06:58

    you can try a more declarative way. I changed your code to reflect this. You just need to remind that a component will refresh and call render in every state/props change. So, we can create the class of your element inside render method.

    import React from 'react'
    
    export default class myComponent extends React.Component {
      constructor() {
        super();
        this.state = { clicked: false };
        this.handleClick = this.handleClick.bind(this);
      }
    
      render() {
        let btnClass = 'glyphicon'
        if(this.state.clicked){
          btnClass+=' active'
        }
        return (
          
     
    ); } handleClick() { this.setState({ clicked: !this.state.clicked }) } }

提交回复
热议问题