ReactJS - How to change style and class of react component?

前端 未结 2 1783
温柔的废话
温柔的废话 2021-02-04 06:39

I\'d like to be able to change the style and className of a component before it\'s rendered, outside of it\'s render function. I\'ve got more going on

相关标签:
2条回答
  • 2021-02-04 06:54

    you can try this game

    componentDidMount() {
      document.querySelector('.yourClassName').style = 'your: style'
    }
    
    0 讨论(0)
  • 2021-02-04 07:01

    React elements are designed to be immutable; usually your app will be easiest to understand if you restructure it to build the proper props upfront instead of mutating them later, and React assumes that this is the case. That said, you can use React.cloneElement to get the effect you want:

    render: function() {
        return React.cloneElement(this.doRender(), {
            style: {border: '1px solid red'}
        });
    },
    

    (Note that if your doRender() function returned a custom component then changing the props would change that component's props, not the underlying DOM component that gets produced. There's no way to render it down to a DOM component and change that component's props, short of manually mutating the DOM in componentDidMount.)

    0 讨论(0)
提交回复
热议问题