我正在ReactJS中重写一个基于AngularJS的现有应用程序。在应用程序中,用户可以提供 CSS 样式字符串来设置某些元素的样式。在 AngularJS 中这没有问题,我只是将“style”属性设置为给定的字符串。在 ReactJS 中我不能再这样做了,因为 ReactJS 需要一个样式对象。我不想改变应用程序的行为,并要求用户现在提供一个与 ReactJS 兼容的样式对象。 ReactJS 有没有办法只使用纯 CSS 样式字符串来设置元素的样式?
您可以设置样式字符串setAttribute('style', ...)
in 组件已挂载 https://facebook.github.io/react/docs/component-specs.html#mounting-componentdidmount and 组件更新 https://facebook.github.io/react/docs/component-specs.html#updating-componentdidupdate.
您只需要能够获取对 React 创建的 DOM 节点的引用。您可以使用refs https://facebook.github.io/react/docs/more-about-refs.html为了那个原因。
这是一个例子。该组件接受一个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;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)