我正在学习反应,我有一些代码等待将鼠标悬停在按钮上,然后在您悬停的图像上应用不透明的白色覆盖(这样可行):
class Product extends Component {
constructor(props) {
super(props);
// 1. bind your functions in the constructor.
this.mouseOver = this.mouseOver.bind(this);
this.mouseOut = this.mouseOut.bind(this);
this.state = {
hover: false
};
}
// 2. bind it with fat arrows.
mouseOver = () => {
this.setState({hover: true});
}
mouseOut() {
this.setState({hover: false});
}
render() {
return (
<Link to={"/products/"+this.props.value.uid}>
<button className="Product" onMouseEnter={this.mouseOver.bind(this)} onMouseLeave={this.mouseOut.bind(this)}>
<img className="ImageGrid" src={this.props.value.media}/>
{this.state.hover ? (
<div className="ImageOverlay">
<div className="TextOverlay">
<p><b>{this.props.value.name}</b></p>
<p>${this.props.value.price}</p>
</div>
</div>) : null}
</button>
</Link>
);
}
}
我的问题是......让我们说,不是在这个组件渲染的图像上添加叠加,我想改变由另一个组件渲染的图像,而不是通过应用叠加div,而是通过更改一些CSS设置所述图像,如应用滤镜:滤镜:灰度(100%)。所以有这个图像:
<img className="PicBox" src={this.state.img[sid-1]} />
由另一个组件呈现。
以下是我认为的策略可能是:
让我的原始组件(我悬停的组件)有一个道具“状态”,跟踪我是否将鼠标悬停在它上面,就像我上面那样。
在渲染ImageX的另一个组件中,我需要以某种方式访问Hover组件的prop,并检查其状态,以决定如何渲染图像(是否使用灰度)。
如何在另一个组件中访问悬停组件的状态?
(或者,如果我的策略已经取消,我们将不胜感激)
答案 0 :(得分:2)
只要您不使用某些状态管理库(例如redux或flux)并且您希望访问组件之间的状态,就需要在这些库之间使用公共父级。 最后你有类似的东西(伪代码):
ParentComponent {
hoverHandler(isHover) {
this.childIsHover = isHover;
}
render() {
<hoverComponent onHover={this.hoverHandler} />
<imageComponent overlay={this.childIsHover} />
}
}
答案 1 :(得分:2)
在与React合作时,你必须考虑谁应该拥有 维持国家的责任。所以在这种情况下,状态应该不 存储在按钮组件中,因为它需要被另一个组件访问 组件不是其子女之一。
相反,您应该创建一个负责存储的父组件 悬停状态,还呈现按钮和图像组件。您可以 将函数绑定到父级,以便在将它们作为props传递给其他函数时 孩子们,他们仍然可以更新父母的状态。
例如,您的父组件可能如下所示:
class Parent extends Component {
constructor () {
super()
this.state = {
hover: false
}
this.updateHoverState = this.updateHoverState.bind(this)
}
updateHoverState (hover) {
this.setState({ hover: hover })
}
render () {
<div>
<ButtonComponent updateHoverState={this.updateHoverState} />
<ImageComponent hover={this.state.hover} />
</div>
}
}
现在,您的按钮组件可以只是一个功能,而不需要维护
任何自己的状态。您可以通过调用更新父状态
this.props.updateHoverState
:
function ButtonComponent (props) {
return (
<button
onMouseEnter={() => this.props.updateHoverState(true)}
onMouseLeave={() => this.props.updateHoverState(false)}
/>
)
}
答案 2 :(得分:1)
在React中,您通常会将属性传递给子组件。因此,而不是试图&#34;达到和超过&#34;进入一个不相关的组件来访问它的状态,你应该访问一个从共享的父组件传递给你的状态。
因此,如果ImageX组件是Product的子组件,则可以将状态直接传递给它SELECT
ITEM,
SUM(CASE
WHEN SALE = 'Yes'
THEN 1
ELSE 0
END) AS TOTAL_DAYS_ON_SALE_DAYS
FROM TABLE 1
WHERE DATES BETWEEN '2/1/2017' AND '4/19/2017'
GROUP BY ITEM
ORDER BY ITEM ASC
。然后,您可以访问ImageX道具中的<ImageX hover={this.state.hover} />
。
如果它不是Product的子级,那么您希望从共享父级传递状态并从两个组件中访问它。
答案 3 :(得分:0)