【发布时间】:2017-09-05 01:14:36
【问题描述】:
如何将 React 组件的计算样式传递给它的子组件?
从<Child /> 的道具访问<Parent /> 计算样式对我来说非常方便。
此外,每次父组件更改时,子组件都必须接收更新的 CSS 属性(例如,用户调整窗口大小并且父组件的宽度设置为 50vw,然后子组件将接收更新的像素大小)。
伪代码:
// App.jsx
class App extends Component {
render() {
return (
<Parent>
<Child />
<Child />
</Parent>
);
}
}
// Child.jsx
class Child extends Component {
render() {
return <h1>Parent's margin-top: {this.props.parentComputedStyle.marginTop}</h1>
}
}
这可能吗?我需要第三方库吗?
编辑 1
想出了一些示例代码来解释我的问题:
import React, { Component, Children, cloneElement } from 'react';
class Parent extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div {...this.props}>
{this.props.children.map((child, index) => {
return (
cloneElement(child, {
key: index.toString(),
parentComputedStyle: this.props.style
})
);
})}
</div>
);
}
}
class Child extends Component {
constructor(props) {
super(props)
}
render() {
return (
<p>Parent width is {this.props.parentComputedStyle.width}</p>
);
}
}
class App extends Component {
constructor() {
super();
}
render() {
return (
<div>
<h1>Styles</h1>
<Parent
style={{
width: '50vw',
backgroundColor: 'rgba(255, 128, 0, 0.4)',
marginTop: '10px'
}}
>
<Child />
<Child />
<Child />
</Parent>
</div>
);
}
}
export default App;
这里的子组件在屏幕上呈现“50vh”,我想要以像素为单位的值(计算的样式,而不是反应样式对象)。
【问题讨论】:
-
你可以使用props
-
是的,但是怎么做?我尝试了
window.getComputedStyle(this.refs.childRef),但在父级的渲染方法中抛出了一个错误。 -
你正在做
{this.props.parentComputedStyle.marginTop},所以你需要将你的样式对象传递给<Children>,就像<Children parentComputedStyle={myStyleObject}>一样,为了更新组件,你应该在你的父组件状态中设置你的样式。 -
让我给你写一个答案
-
问题是,如果我在
render方法中设置状态,它会抛出错误,如果我在componentDidUpdate方法中使用CSS 设置状态,它会进入一个无限调用循环(因为状态变化再次调用render,它调用生命周期方法等等..)。
标签: javascript reactjs