gpt4 book ai didi

javascript - 在 React 中使用纯 CSS 字符串使用内联样式

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:44:05 25 4
gpt4 key购买 nike

我正在重写一个基于 ReactJS 中的 AngularJS 的现有应用程序。在应用程序中,用户可以提供 CSS 样式字符串来设置某些元素的样式。在 AngularJS 中这没有问题,我只是将“style”属性设置为给定的字符串。在 ReactJS 中我不能再这样做了,因为 ReactJS 需要一个样式对象。我不想改变应用程序的行为并要求用户现在提供一个 ReactJS 兼容的样式对象。在 ReactJS 中有什么方法可以只使用纯 CSS 样式字符串来设置元素的样式吗?

最佳答案

您可以使用 setAttribute('style', ...) 设置样式字符串在 componentDidMountcomponentDidUpdate .

您只需要能够获得对 React 创建的 DOM 节点的引用。您可以使用 refs为此。

这是一个例子。该组件接受 styleString prop,并将其设置为 <div/> 上的样式它呈现。

import React from 'react';

class StyledDiv extends React.Component {
componentDidMount() {
this.refs.theDiv.setAttribute('style', this.props.styleString);
}

componentDidUpdate() {
this.refs.theDiv.setAttribute('style', this.props.styleString);
}

render() {
return (
<div ref="theDiv" />
);
}
}
StyledDiv.propTypes = {
styleString: React.PropTypes.string,
};
export default StyledDiv;

关于javascript - 在 React 中使用纯 CSS 字符串使用内联样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33331570/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com