我试图简单地获得width
上渲染的height
之一的<div/>
和Child.js
。 This是一个很好的例子,但就我而言,我没有一个<div/>
,但array
中的containers
是动态渲染的。
[一旦获得这些dimensions
,指向childData.offsetWidth
和childData.offsetHeight
,我想使用setState
并将此信息存储在childDims
中。
问题:
我没有设法将从data
接收的Child.js
限制为instance
的一个this.state.dummyArray
,使得无法使用setState
,因为data
上的callback function
被传递了一次对于component
处的每个rendered
this.state.dummyArray.map(donkey => {...
这里是我的code
import React from "react";
import Child from "./Child";
import "./styles.css";
export default class App extends React.Component {
state = {
childDims: {
width: "",
heigth: ""
}
};
componentDidMount(childData) {
console.log("container dims from child", childData);
}
render() {
return (
<div className="App">
<Child liftContainerDimensions={this.componentDidMount} />
</div>
);
}
}
import React from "react";
export default class Child extends React.Component {
state = {
dummyArray: [1, 2, 3, 4]
};
render() {
return (
<div>
{this.state.dummyArray.map(donkey => {
return (
<div
style={{ border: "1px solid red", margin: "5px" }}
ref={el =>
this.props.liftContainerDimensions((this.container = el))
}
>
{donkey}
</div>
);
})}
</div>
);
}
}
这是我的看法。感觉很奇怪,但这可以满足您的要求。
它使用钩子,因此对您来说可能看起来有些奇怪。