[英]Return multiple HOC components from Array in React JS
我正在嘗試從任何數組聲明並返回多個 HOC,但一直返回“函數作為 React 子級無效”。 錯誤。 有沒有人遇到過這個問題?
JS:
....
const styles = {
fontFamily: "sans-serif",
textAlign: "center"
};
const withRequestAnimationFrame = () => WrappedComponent => {
class RequestAnimationFrame extends Component {
state = {
timeStamp: 0,
newItem: "Test"
};
componentDidMount() {
const min = 1;
const max = 100;
const rand = Math.floor(Math.random() * (max - min + 1)) + min;
this.setState({ timeStamp: this.state.timeStamp + rand });
}
render() {
return (
<WrappedComponent {...this.state} {...this.props} />
)
}
}
return RequestAnimationFrame;
};
const App = ({ timeStamp, newItem }) => (
<div style={styles}>
<h1>{timeStamp}</h1>
<p>{newItem}</p>
</div>
);
const arrayItems = ["EnhancedApp", "EnhancedApp2"];
const Products = ({ items }) => {
return (
items.map((item, index) => (
item = withRequestAnimationFrame()(App)
))
)
};
function Product() {
return (
<div>
<Products items={arrayItems} />
</div>
)
}
render(<Product />, document.getElementById("root"));
這條線是問題所在:
item = withRequestAnimationFrame()(App)
您在那里所做的是將 withRequestAnimationFrame()(App) function 的結果分配給絕對不是您想要的項目。 我假設您想在那里呈現 withRequestAnimationFrame 組件的多個實例。 你可以這樣做:
items.map((item, index) => ( const NewComponent = withRequestAnimationFrame(item)(App); return <NewComponent key={index}/> ))
第二個問題是您沒有將 item prop 傳遞給包裝的組件。 要傳遞項目道具,您應該這樣做:
const withRequestAnimationFrame = (item) => WrappedComponent => { class RequestAnimationFrame extends React.Component { state = { timeStamp: 0, newItem: item };
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.