简体   繁体   English

ReactJS - 如何更改反应组件的样式和类?

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

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. 我希望能够在渲染之前更改组件的styleclassName ,而不是它的渲染功能。 I've got more going on than I'm showing here, but this is the basic idea, being able to set the style and className as properties somehow: 我有更多的事情比我在这里展示的更多,但这是基本的想法,能够以某种方式将样式和className设置为属性:

The following works only if the "style" variable is moved inside the render function, and added to the div like normal (eg <div style={style}> ). 以下情况仅适用于“style”变量在render函数内移动,并像普通(例如<div style={style}> )一样添加到div中。 How can I make the following work? 我该如何进行以下工作?

JS Fiddle that doesnt work JS Fiddle不起作用

EDIT: Working JS Fiddle here ! 编辑: 在这里工作JS小提琴!

/** @jsx React.DOM */

var Main = React.createClass({

    render: function() {
       var result = this.doRender();

       var style = {
         border:'1px solid red'
       };

       result.style = style;

       return result;
    },

    doRender: function() {
        return (
          <div>Test</div>
        );
    }
});

React.renderComponent(<Main/>, document.body);

React elements are designed to be immutable; React元素被设计为不可变的; 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. 通常你的应用程序将最容易理解,如果你重新构建它以建立适当的道具而不是以后改变它们,并且React假设是这种情况。 That said, you can use React.cloneElement to get the effect you want: 也就是说,您可以使用React.cloneElement来获得所需的效果:

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 .) (请注意,如果你的doRender()函数返回了一个自定义组件,那么更改道具会改变该组件的props,而不是生成的底层DOM组件。没有办法将它渲染为DOM组件并更改该组件的道具,简短手动改变componentDidMount的DOM。)

you can try this game 你可以尝试这个游戏

componentDidMount() {
  document.querySelector('.yourClassName').style = 'your: style'
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM