[英]How to update child's(from the created list) props from parent
这可能涉及其他相关的一般性问题,例如如何从父级更新子级组件,尽管我想听听我对以下方案的设计解决方案的任何合理判断。
我有一个父类,我在其中存储2个子对象的css属性。
import React from 'react'
import Item from './item/Item'
class Small_gallery extends React.Component {
constructor(props) {
super(props);
this.state = {
chosenVal: 0,
};
this.listObjParams = [
// Style 1
{
left: 300,
zIndex: 0
},
//Style 2
{
left: 320,
zIndex: 1
}
];
this.handleClick = this.handleClick.bind(this);
this.calculateShift = this.applyNewStyle.bind(this);
this.listItems = this.listObjParams.map((objStyle, i) =>
<Item
key={i}
id={i}
objStyle={objStyle}
onClick={this.handleClick}
/>
);
}
handleClick = (indexFromChild) => {
this.setState({chosenVal: indexFromChild});
this.applyNewStyle(indexFromChild)
};
applyNewStyle = (clickedIndex) => {
if (clickedIndex === 0) {
// somehow I want to apply new css style 2 to the clicked? <Item> child
};
render() {
return (
<div>
{this.listItems}
</div>
)
}
子组件相当琐碎:
class Item extends React.Component {
constructor(props) {
super(props)
}
render() {
return (
<div
onClick={(e) => {
e.preventDefault();
this.props.onClick(this.props.id)
}}
style={{
left: this.props.objStyle.left,
zIndex: this.props.objStyle.zIndex
}}
>
</div>
);
}
}
问题是:如何将样式1或样式2应用于单击的Item组件(取决于我要返回的索引)? 我已经阅读了有关getDerivedStateFromProps
而不是在这里使用不推荐使用的componentWillReceiveProps
https://hackernoon.com/replacing-componentwillreceiveprops-with-getderivedstatefromprops-c3956f7ce607,但这不是我的解决方案。
我预计创建的项目数将来会增长到10-20,因此在创建项目时用this.listObjParams
填充项目状态是没有意义的,或者我在这里错了吗?
对于<Item/>
您可以使用简单的功能组件。 最适合简单而不是那么复杂的用例。
例如
const Item = ({ id, clickHandler, objStyle }) => (
<div
onClick={e => {
e.preventDefault();
clickHandler(id);
}}
style={...objStyle}
/>
);
PureComponent
也将根据道具变更进行更新。
在完整类的组件中,您可以使用shouldComponentUpdate()
强制更改道具更改。 无需使用getDerivedStateFromProps
复制数据(进入状态)(取决于用例)。
搜索一些教程(例如典型的待办事项示例),因为您不了解状态管理,更新等。
配售listObjParams
以外的state
也不会强迫重新描绘上更新。 顺便说一句,它看起来更像是一个样式池-也许您应该有一个子params数组...您可以将其与样式索引数组结合使用,也可以分别保留它们(并作为道具传递)。
constructor(props) {
super(props);
this.state = {
// chosenVal: 0, // temporary handler param? probably no need to store in the state
listObjStyles: [0, 1] // style indexes
};
this.stylePool = [
// Style 1
{
left: 300,
zIndex: 0
},
//Style 2
{
left: 320,
zIndex: 1
}
];
用法:
this.listItems = this.state.listObjStyles.map((styleIndex, i) => <Item
key={i}
id={i}
objStyle={this.stylePool[ styleIndex ]}
clickHandler={this.handleClick}
/>
更新listObjStyles
( setState()
)将强制重新渲染,而不会更新this.stylePool
(如果需要重新渲染,则移动到该state
)。
当然, stylePool
可以为不同的项目“状态”包含2种以上的样式。 您可以为选定的,喜欢的,与众不同的样式制作样式-通过将索引存储在数组中,可以将它们中的任何一种与自定义逻辑混合(仅选择一个,很多喜欢)。
10-20个项目不是您需要特殊优化(避免避免不必要的重新渲染)的情况。
我在下面有一个工作示例,以便介绍我所做的事情:
<Item />
。 activeStyles || inactiveStyles
activeStyles || inactiveStyles
是基于与对象ID(来自数组prop = items
)匹配的currentId
。 import React from "react";
const inactiveStyles = {
left: 300,
zIndex: 0,
backgroundColor: "#E9573F"
};
const activeStyles = {
left: 320,
zIndex: 1,
backgroundColor: "#00B1E1"
};
const inboundItems = [
{
id: 0
},
{
id: 1
},
{
id: 2
}
];
// Note - added to show it working not needed
const defaultStyles = {
display: "block",
border: "1px solid black",
width: 50,
height: 50
};
export const Item = ({ id, onClick, style }) => (
<>
<pre>{JSON.stringify({ styles: style }, null, 2)}</pre>
<div
{...{ id }}
style={{ ...defaultStyles, ...style }}
onClick={e => {
e.preventDefault();
onClick(id);
}}
/>
</>
);
export const SmallGallery = ({ items = inboundItems }) => {
const [currentId, setCurrentId] = React.useState(null);
const getStyles = selectedId => {
return currentId === selectedId ? activeStyles : inactiveStyles;
};
return items.map(({ id, ...item }) => (
<Item
key={id}
{...{ id }}
{...item}
style={getStyles(id)}
onClick={selectedId => setCurrentId(selectedId)}
/>
));
};
export default SmallGallery;
让我知道您的想法,我添加了一个屏幕截图以显示要添加的样式。
总结一下我所做的所有工作,基于两个答案(仍然是一个相当有趣的示例):
家长:
import Item from './item/Item'
class Small_gallery extends React.Component {
constructor(props) {
super(props);
this.state = {
listObjStyles: [0, 1]
};
this.stylePool = [
{
position: 'absolute',
width: 600,
left: 300,
height: 100,
backgroundColor: '#000',
zIndex: 0,
transition: 'all 1s ease'
},
{
position: 'absolute',
width: 600,
left: 720,
height: 350,
backgroundColor: '#ccc',
zIndex: 1,
transition: 'all 2s ease'
}]
}
handleClick = (indexFromChild) => {
console.log(indexFromChild)
if (indexFromChild === 0) {
this.setState({
listObjStyles: [1, 0]
})
} else if (indexFromChild === 1) {
this.setState({
listObjStyles: [0, 1]
})
}
}
render() {
return (
<>
<div style={{display: 'flex', margin: 40}}>
{this.state.listObjStyles.map((styleIndex, i) =>
<Item
key={i}
id={i}
objStyle={this.stylePool[styleIndex]}
onClick={this.handleClick}
/>
)}
</div>
</>)
}
}
儿童:
const Item = ({id, onClick, objStyle}) => (
<div
onClick={e => {
e.preventDefault();
onClick(id)
}}
style={{...objStyle}}
/>
);
export default Item
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.