ReactJS - 如何更改反应组件的样式和类? [英] ReactJS - How to change style and class of react component?

查看:294
本文介绍了ReactJS - 如何更改反应组件的样式和类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够在呈现组件之前更改组件的样式 className 它的渲染功能。我有更多的事情要比我在这里展示的更多,但这是基本的想法,能够以某种方式将样式和className设置为属性:

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 than I'm showing here, but this is the basic idea, being able to set the style and className as properties somehow:

以下仅当style变量在render函数内移动时才有效,并且正常情况下添加到div中(例如< div style = {style}> )。如何进行以下工作?

The following works only if the "style" variable is moved inside the render function, and added to the div like normal (e.g. <div style={style}> ). How can I make the following work?

JS Fiddle that that不起作用

编辑:在这里工作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元素设计为不可变的;通常你的应用程序将最容易理解,如果你重新构建它以建立适当的道具而不是以后改变它们,并且React假设是这种情况。也就是说,您可以使用 React.cloneElement 获得你想要的效果:

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'}
    });
},

(请注意,如果你的 doRender()函数返回一个自定义组件,然后更改道具将改变该组件的道具,而不是生成的底层DOM组件。没有办法将其渲染为DOM组件并更改该组件的道具,缺少手动在 componentDidMount 中改变DOM。)

(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.)

这篇关于ReactJS - 如何更改反应组件的样式和类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆